Home > Enterprise >  Tkinter displaying output in a entry box using when using nested classes
Tkinter displaying output in a entry box using when using nested classes

Time:03-11

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()

CodePudding user response:

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()
  • Related