使用嵌套类时,Tkinter 在输入框中显示输出

发布于 2025-01-13 08:45:43 字数 5279 浏览 2 评论 0原文

所以问题是当使用第二个窗口(您使用下一页按钮导航到该窗口)时。当我在每个框中输入8位二进制数时,前提是它应该将它们加在一起并在标记的添加二进制框中显示它们。但目前它似乎没有正确设置值来做到这一点,它只是在命令行中打印我设置的值,这表明该方法正在工作。

任何有关如何解决此问题的见解将不胜感激。 仅供参考,是的,它是故意为 8 位二进制文​​件完成的,是的,它需要使用嵌套类。因为这就是作业需要使用的。

很抱歉,如果这只是一个小错误,而且我在某个地方很笨拙,但我已经被难住了一段时间了。

这是修改后的最小可重现示例:

from tkinter import * 
from tkinter.ttk import *
from tkinter import ttk
import tkinter
import math
import sys

def BinaryAddition(value1, value2):
    if len(value1) != 8:
        return "Binary number 1 is not 8 bits"
    if len(value2) != 8:
        return "Binary number 2 is not 8 bits"
    res = bin(int(value1,2) + int(value2,2))
    Ob = res[2:]#removing the ob prefix 
    return Ob

class MainWindow():
    
    FONT = ("Consolas", 16)
    TxtMaxLen = 32


    class SecondWindow():
        def __init__(self2):
            self2._window = tkinter.Tk()
            self2._window.title("Converter")
            self2._window["bg"] = "#EFFFA3"
            f = ("Times bold", 16)
            TxtMaxLen = 32
            self2._window.geometry("820x240")

            label = tkinter.Label(self2._window, text="Binary Number 1: ", font= f)#label defined for number input box 
            label.grid(row=0, column=0, padx=10, pady=5)#positioning / dimensions of input box
            
            label = tkinter.Label(self2._window, text="Binary Number 2: ", font= f)#label defined for number input box 
            label.grid(row=1, column=0, padx=10, pady=5)#positioning / dimensions of input box

            #input box for binary number 1 
            self2.input1 = tkinter.Entry(self2._window, width= TxtMaxLen, font= f) #defined input box 
            self2.input1.grid(row=0, column=1, pady=5)#postioning / dimensions of input box
            self2.input1.focus()

            #input box for binary number 2 
            self2.input2 = tkinter.Entry(self2._window, width=TxtMaxLen, font= f) #defined input box 
            self2.input2.grid(row=1, column=1, pady=5)#postioning / dimensions of input box
            self2.input2.focus()

            separator = tkinter.ttk.Separator(self2._window,orient=tkinter.HORIZONTAL)
            separator.grid(row=3, column=1, pady=15)


            self2._bt_Add = tkinter.Button(self2._window, text="Add", font= f, command = self2.AdditionSelection)#button defined for bin  
            self2._bt_Add.grid(row=1, column=2, padx=5, pady=5)#postioning / dimensions of button box        

            #labels for output box of combined binary number
            label = tkinter.Label(self2._window, text="Added Binary: ", font= f)#label defined for number input box 
            label.grid(row=4, column=0, padx=10, pady=5)#positioning / dimensions of input box

            #label for output  box for if there was or was not an overflow
            label = tkinter.Label(self2._window, text="OverFlow: ", font= f)#label defined for number input box 
            label.grid(row=5, column=0, padx=10, pady=5)#positioning / dimensions of input box

            #output box for the added binary number
            self2.stringvar_Combined = tkinter.StringVar()
            txt_output = tkinter.Entry(self2._window, textvariable=self2.stringvar_Combined, width=TxtMaxLen, state="readonly", font= f)#entry box set to readonly to act as a display box 
            txt_output.grid(row=4, column=1, pady=5)
            
            #output box for if there was or was not an overflow
            self2._stringvar_OverFlow = tkinter.StringVar()
            txt_output = tkinter.Entry(self2._window, textvariable=self2._stringvar_OverFlow, width=TxtMaxLen, state="readonly", font= f)#entry box set to readonly to act as a display box 
            txt_output.grid(row=5, column=1, pady=5)

            separator = tkinter.ttk.Separator(self2._window,orient=tkinter.VERTICAL)
            separator.grid(row=3, column=2, pady=15)


            PrevPageButton = tkinter.Button(self2._window, text="Previous Page", font=f, command=MainWindow)
            PrevPageButton.grid(row=5, column = 2, padx = 5,pady = 5)


        def set_values(self, BinAdd):
            self.stringvar_Combined.set(BinAdd)
 
        def AdditionSelection(self2):
                    try:
                        BinV1 = self2.input1.get().strip().replace(" ", "")
                        BinV2 = self2.input2.get().strip().replace(" ", "")
                        BinAdd = BinaryAddition(BinV1, BinV2)

                        self2.set_values(BinAdd)
                        print(BinAdd)
                        print("hi there")

                    except Exception as ex:
                        print("NOPE it aint workin")

    def __init__(self):
        self._window = tkinter.Tk()
        self._window.title("Converter")
        self._window["bg"] = "#20A3FF" #background colour
        self._window.geometry("820x240")#setting window size

        #setting up button for binary additon page
        NextPageButton = tkinter.Button(self._window, text="Next Page", font=MainWindow.FONT, command=self.SecondWindow)
        NextPageButton.grid(row=4, column = 3, padx = 5,pady = 5)
        self._window.destroy
        
    def mainloop(self):
        self._window.mainloop()

if __name__ == "__main__":
    win = MainWindow()
    win.mainloop()

So the problem is that when using the second window (which you navigate to using the next page button). When I enter the 8-bit binary numbers in each box the premise is that it should add them together and display them in the labeled added binary box. but at the moment it does not seem to set the value correctly to do that and it just prints in the command line what I set it to which shows that the method is working.

Any insight into how to fix this would be greatly appreciated.
FYI yes it is deliberately done for 8-bit binary and yes it needs to use nested classes. as that is what the assignment requires the use of.

sorry if it is just a small error and I am being clumsy somewhere but I have been stumped for some time.

Here is the revised minimal reproducible example:

from tkinter import * 
from tkinter.ttk import *
from tkinter import ttk
import tkinter
import math
import sys

def BinaryAddition(value1, value2):
    if len(value1) != 8:
        return "Binary number 1 is not 8 bits"
    if len(value2) != 8:
        return "Binary number 2 is not 8 bits"
    res = bin(int(value1,2) + int(value2,2))
    Ob = res[2:]#removing the ob prefix 
    return Ob

class MainWindow():
    
    FONT = ("Consolas", 16)
    TxtMaxLen = 32


    class SecondWindow():
        def __init__(self2):
            self2._window = tkinter.Tk()
            self2._window.title("Converter")
            self2._window["bg"] = "#EFFFA3"
            f = ("Times bold", 16)
            TxtMaxLen = 32
            self2._window.geometry("820x240")

            label = tkinter.Label(self2._window, text="Binary Number 1: ", font= f)#label defined for number input box 
            label.grid(row=0, column=0, padx=10, pady=5)#positioning / dimensions of input box
            
            label = tkinter.Label(self2._window, text="Binary Number 2: ", font= f)#label defined for number input box 
            label.grid(row=1, column=0, padx=10, pady=5)#positioning / dimensions of input box

            #input box for binary number 1 
            self2.input1 = tkinter.Entry(self2._window, width= TxtMaxLen, font= f) #defined input box 
            self2.input1.grid(row=0, column=1, pady=5)#postioning / dimensions of input box
            self2.input1.focus()

            #input box for binary number 2 
            self2.input2 = tkinter.Entry(self2._window, width=TxtMaxLen, font= f) #defined input box 
            self2.input2.grid(row=1, column=1, pady=5)#postioning / dimensions of input box
            self2.input2.focus()

            separator = tkinter.ttk.Separator(self2._window,orient=tkinter.HORIZONTAL)
            separator.grid(row=3, column=1, pady=15)


            self2._bt_Add = tkinter.Button(self2._window, text="Add", font= f, command = self2.AdditionSelection)#button defined for bin  
            self2._bt_Add.grid(row=1, column=2, padx=5, pady=5)#postioning / dimensions of button box        

            #labels for output box of combined binary number
            label = tkinter.Label(self2._window, text="Added Binary: ", font= f)#label defined for number input box 
            label.grid(row=4, column=0, padx=10, pady=5)#positioning / dimensions of input box

            #label for output  box for if there was or was not an overflow
            label = tkinter.Label(self2._window, text="OverFlow: ", font= f)#label defined for number input box 
            label.grid(row=5, column=0, padx=10, pady=5)#positioning / dimensions of input box

            #output box for the added binary number
            self2.stringvar_Combined = tkinter.StringVar()
            txt_output = tkinter.Entry(self2._window, textvariable=self2.stringvar_Combined, width=TxtMaxLen, state="readonly", font= f)#entry box set to readonly to act as a display box 
            txt_output.grid(row=4, column=1, pady=5)
            
            #output box for if there was or was not an overflow
            self2._stringvar_OverFlow = tkinter.StringVar()
            txt_output = tkinter.Entry(self2._window, textvariable=self2._stringvar_OverFlow, width=TxtMaxLen, state="readonly", font= f)#entry box set to readonly to act as a display box 
            txt_output.grid(row=5, column=1, pady=5)

            separator = tkinter.ttk.Separator(self2._window,orient=tkinter.VERTICAL)
            separator.grid(row=3, column=2, pady=15)


            PrevPageButton = tkinter.Button(self2._window, text="Previous Page", font=f, command=MainWindow)
            PrevPageButton.grid(row=5, column = 2, padx = 5,pady = 5)


        def set_values(self, BinAdd):
            self.stringvar_Combined.set(BinAdd)
 
        def AdditionSelection(self2):
                    try:
                        BinV1 = self2.input1.get().strip().replace(" ", "")
                        BinV2 = self2.input2.get().strip().replace(" ", "")
                        BinAdd = BinaryAddition(BinV1, BinV2)

                        self2.set_values(BinAdd)
                        print(BinAdd)
                        print("hi there")

                    except Exception as ex:
                        print("NOPE it aint workin")

    def __init__(self):
        self._window = tkinter.Tk()
        self._window.title("Converter")
        self._window["bg"] = "#20A3FF" #background colour
        self._window.geometry("820x240")#setting window size

        #setting up button for binary additon page
        NextPageButton = tkinter.Button(self._window, text="Next Page", font=MainWindow.FONT, command=self.SecondWindow)
        NextPageButton.grid(row=4, column = 3, padx = 5,pady = 5)
        self._window.destroy
        
    def mainloop(self):
        self._window.mainloop()

if __name__ == "__main__":
    win = MainWindow()
    win.mainloop()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

很快妥协 2025-01-20 08:45:43

主要问题:要创建第二个窗口,您应该使用 Toplevel() 而不是 Tk()

当我使用 Toplevel 时,它会在窗口中显示文本。


如果您只想看到一个窗口,那么您应该首先 destroy() 旧窗口,然后您可以使用 Tk() 创建新窗口(使用新的 主循环())。

但这可能会带来其他问题。它删除窗口中的所有值,当您返回某个窗口时,它将不再具有旧值。最好创建两个 Frame 并在 Tk() 中替换它们而不破坏它们 - 并且它们将保留旧值。


其余只是如何创建更具可读性的代码的建议:

  • 不要将 SecondWindow 放入 MainWindow 中,
  • 不要使用 self2
  • 使用 lower_case_names< /code> 用于函数和变量

更多信息请参见 PEP 8 -- Python 风格指南代码


进行了一些更改的代码。

它显示值(我还添加了 .zfill(8) 以显示 8 位数字)

但是每次更改窗口时都会创建新窗口 - 下一个上一个 code> - 所以你可能有两个主窗口等。它需要更多的更改。

import tkinter   # PEP8: `import *` is not preferred
from tkinter import ttk
import math
import sys

def binary_addition(value1, value2):
    if len(value1) != 8:
        return "Binary number 1 is not 8 bits"
    if len(value2) != 8:
        return "Binary number 2 is not 8 bits"
    res = bin(int(value1,2) + int(value2,2))
    return res[2:].zfill(8) #removing the ob prefix 


class MainWindow():
    
    FONT = ("Consolas", 16)
    TxtMaxLen = 32

    def __init__(self):
        self._window = tkinter.Tk()
        self._window.title("Converter")
        self._window["bg"] = "#20A3FF" #background colour
        self._window.geometry("820x240")#setting window size

        #setting up button for binary additon page
        next_page_button = tkinter.Button(self._window, text="Next Page", font=MainWindow.FONT, command=SecondWindow)
        next_page_button.grid(row=4, column = 3, padx = 5,pady = 5)
        
    def mainloop(self):
        self._window.mainloop()

class SecondWindow():
    
    def __init__(self):
        self._window = tkinter.Toplevel()
        self._window.title("Converter")
        self._window["bg"] = "#EFFFA3"
        
        f = ("Times bold", 16)
        TxtMaxLen = 32
        
        self._window.geometry("820x240")

        label = tkinter.Label(self._window, text="Binary Number 1: ", font= f)#label defined for number input box 
        label.grid(row=0, column=0, padx=10, pady=5)#positioning / dimensions of input box
        
        label = tkinter.Label(self._window, text="Binary Number 2: ", font= f)#label defined for number input box 
        label.grid(row=1, column=0, padx=10, pady=5)#positioning / dimensions of input box

        #input box for binary number 1 
        self.input1 = tkinter.Entry(self._window, width= TxtMaxLen, font= f) #defined input box 
        self.input1.grid(row=0, column=1, pady=5)#postioning / dimensions of input box
        self.input1.focus()

        #input box for binary number 2 
        self.input2 = tkinter.Entry(self._window, width=TxtMaxLen, font= f) #defined input box 
        self.input2.grid(row=1, column=1, pady=5)#postioning / dimensions of input box
        self.input2.focus()

        separator = tkinter.ttk.Separator(self._window,orient=tkinter.HORIZONTAL)
        separator.grid(row=3, column=1, pady=15)


        self._bt_add = tkinter.Button(self._window, text="Add", font= f, command = self.addition_selection)#button defined for bin  
        self._bt_add.grid(row=1, column=2, padx=5, pady=5)#postioning / dimensions of button box        

        #labels for output box of combined binary number
        label = tkinter.Label(self._window, text="Added Binary: ", font= f)#label defined for number input box 
        label.grid(row=4, column=0, padx=10, pady=5)#positioning / dimensions of input box

        #label for output  box for if there was or was not an overflow
        label = tkinter.Label(self._window, text="OverFlow: ", font= f)#label defined for number input box 
        label.grid(row=5, column=0, padx=10, pady=5)#positioning / dimensions of input box

        #output box for the added binary number
        self.stringvar_combined = tkinter.StringVar()
        txt_output = tkinter.Entry(self._window, textvariable=self.stringvar_combined, width=TxtMaxLen, state="readonly", font= f)#entry box set to readonly to act as a display box 
        txt_output.grid(row=4, column=1, pady=5)
        
        #output box for if there was or was not an overflow
        self._stringvar_overflow = tkinter.StringVar()
        txt_output = tkinter.Entry(self._window, textvariable=self._stringvar_overflow, width=TxtMaxLen, state="readonly", font= f)#entry box set to readonly to act as a display box 
        txt_output.grid(row=5, column=1, pady=5)

        separator = tkinter.ttk.Separator(self._window,orient=tkinter.VERTICAL)
        separator.grid(row=3, column=2, pady=15)

        prev_page_button = tkinter.Button(self._window, text="Previous Page", font=f, command=MainWindow)
        prev_page_button.grid(row=5, column = 2, padx = 5,pady = 5)

    def set_values(self, value):
        self.stringvar_combined.set(value)

    def addition_selection(self):
        try:
            bin_1 = self.input1.get().strip().replace(" ", "")
            bin_2 = self.input2.get().strip().replace(" ", "")
            bin_add = binary_addition(bin_1, bin_2)

            self.set_values(bin_add)
            print("bin_add:", bin_add)

        except Exception as ex:
            print("NOPE it aint workin", ex)


if __name__ == "__main__":
    win = MainWindow()
    win.mainloop()

Main problem: to create second window you should use Toplevel() instead of Tk().

And when I use Toplevel then it show text in window.


And if you want to see only one window then you should first destroy() old window and later you can use Tk() to create new window (with new mainloop()).

But this can make other problem. It delete all values in window and when you will back some window then it will not have old value. It may be better to create two Frames and replace them in Tk() without destroying them - and they will keep old values.


Rest are only suggestions how to create more readable code:

  • don't put SecondWindow inside MainWindow
  • don't use self2
  • use lower_case_names for functions and variables

More in PEP 8 -- Style Guide for Python Code


Code with some changes.

It display value (I also added .zfill(8) to display 8 digits)

But this creates new window everytime when you change window - next or previous - so you may have two main windows, etc. It would need more changes.

import tkinter   # PEP8: `import *` is not preferred
from tkinter import ttk
import math
import sys

def binary_addition(value1, value2):
    if len(value1) != 8:
        return "Binary number 1 is not 8 bits"
    if len(value2) != 8:
        return "Binary number 2 is not 8 bits"
    res = bin(int(value1,2) + int(value2,2))
    return res[2:].zfill(8) #removing the ob prefix 


class MainWindow():
    
    FONT = ("Consolas", 16)
    TxtMaxLen = 32

    def __init__(self):
        self._window = tkinter.Tk()
        self._window.title("Converter")
        self._window["bg"] = "#20A3FF" #background colour
        self._window.geometry("820x240")#setting window size

        #setting up button for binary additon page
        next_page_button = tkinter.Button(self._window, text="Next Page", font=MainWindow.FONT, command=SecondWindow)
        next_page_button.grid(row=4, column = 3, padx = 5,pady = 5)
        
    def mainloop(self):
        self._window.mainloop()

class SecondWindow():
    
    def __init__(self):
        self._window = tkinter.Toplevel()
        self._window.title("Converter")
        self._window["bg"] = "#EFFFA3"
        
        f = ("Times bold", 16)
        TxtMaxLen = 32
        
        self._window.geometry("820x240")

        label = tkinter.Label(self._window, text="Binary Number 1: ", font= f)#label defined for number input box 
        label.grid(row=0, column=0, padx=10, pady=5)#positioning / dimensions of input box
        
        label = tkinter.Label(self._window, text="Binary Number 2: ", font= f)#label defined for number input box 
        label.grid(row=1, column=0, padx=10, pady=5)#positioning / dimensions of input box

        #input box for binary number 1 
        self.input1 = tkinter.Entry(self._window, width= TxtMaxLen, font= f) #defined input box 
        self.input1.grid(row=0, column=1, pady=5)#postioning / dimensions of input box
        self.input1.focus()

        #input box for binary number 2 
        self.input2 = tkinter.Entry(self._window, width=TxtMaxLen, font= f) #defined input box 
        self.input2.grid(row=1, column=1, pady=5)#postioning / dimensions of input box
        self.input2.focus()

        separator = tkinter.ttk.Separator(self._window,orient=tkinter.HORIZONTAL)
        separator.grid(row=3, column=1, pady=15)


        self._bt_add = tkinter.Button(self._window, text="Add", font= f, command = self.addition_selection)#button defined for bin  
        self._bt_add.grid(row=1, column=2, padx=5, pady=5)#postioning / dimensions of button box        

        #labels for output box of combined binary number
        label = tkinter.Label(self._window, text="Added Binary: ", font= f)#label defined for number input box 
        label.grid(row=4, column=0, padx=10, pady=5)#positioning / dimensions of input box

        #label for output  box for if there was or was not an overflow
        label = tkinter.Label(self._window, text="OverFlow: ", font= f)#label defined for number input box 
        label.grid(row=5, column=0, padx=10, pady=5)#positioning / dimensions of input box

        #output box for the added binary number
        self.stringvar_combined = tkinter.StringVar()
        txt_output = tkinter.Entry(self._window, textvariable=self.stringvar_combined, width=TxtMaxLen, state="readonly", font= f)#entry box set to readonly to act as a display box 
        txt_output.grid(row=4, column=1, pady=5)
        
        #output box for if there was or was not an overflow
        self._stringvar_overflow = tkinter.StringVar()
        txt_output = tkinter.Entry(self._window, textvariable=self._stringvar_overflow, width=TxtMaxLen, state="readonly", font= f)#entry box set to readonly to act as a display box 
        txt_output.grid(row=5, column=1, pady=5)

        separator = tkinter.ttk.Separator(self._window,orient=tkinter.VERTICAL)
        separator.grid(row=3, column=2, pady=15)

        prev_page_button = tkinter.Button(self._window, text="Previous Page", font=f, command=MainWindow)
        prev_page_button.grid(row=5, column = 2, padx = 5,pady = 5)

    def set_values(self, value):
        self.stringvar_combined.set(value)

    def addition_selection(self):
        try:
            bin_1 = self.input1.get().strip().replace(" ", "")
            bin_2 = self.input2.get().strip().replace(" ", "")
            bin_add = binary_addition(bin_1, bin_2)

            self.set_values(bin_add)
            print("bin_add:", bin_add)

        except Exception as ex:
            print("NOPE it aint workin", ex)


if __name__ == "__main__":
    win = MainWindow()
    win.mainloop()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文