Tkinter displaying output in a entry box using when using nested classes - python

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

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

How to insert values created by a loop function to tkinter text boxes which are also created automatically with a loop function

Hi I'm trying to write a code that calculates the net present values of the installments. The code runs perfect up to a point where I can't insert the calculated values in to the tkinter text boxes individually.
For example the code is asking the yearly interest rate and the input can be 15. The list price of an house can be 1000000 and the down payment can be 0.2 which is %20 of the list price. And we can input 12 as the number of installments.
Down payment will be calculated by multiplying 1000000 with 0.2 and gives 200000. And the execution will be inserted to the first tkinter text box. But when the calculation done for the net present values of the installments, all of them appear inside last tkinter text box rather than appearing individually.
Here is the code;
# This program is to create a payment schedule for the customers and check whether
# the payment plan is suitable for the seller in terms of net present value.
from tkinter import *
window=Tk()
# This part asks the number of installments and creates the desired amount of text boxes.
def create():
for y in range(number_of_installments.get()):
t11 = Label(window,text= '%s.Installment'%(y+1),foreground="green")
t11.grid(row = y+2,column=0)
for y in range(number_of_installments.get()):
ttt = Text(window, height=1, width=20, foreground="red")
ttt.grid(row = y+2,column=1)
#Net present values of the installments are calculated in this part.
def NPV_calculation():
interest_rate = [pow(1+0.0125,i) for i in range(1,int(number_of_installments.get())+1)]
installment_amount = (float(list_price.get())-(float(list_price.get())*float(downpayment_percentage.get())))/(float(number_of_installments.get()))
calculation = [installment_amount/i for i in interest_rate]
ttt.insert(END,calculation)
downpayment_calculation()
NPV_calculation()
#Downpayment calculated by entering a value between 0 to 1. For example if 0.2 is typed in the textbox it will multiply the list price by %20.
def downpayment_calculation():
Downpayment = float(list_price.get())*float(downpayment_percentage.get())
t0.insert(END,Downpayment)
#Entry boxes
number_of_installments = IntVar(value="")
installment = Entry(window, textvariable=number_of_installments)
installment.grid(row=3,column=3)
interest_value = StringVar()
interest = Entry(window, textvariable=interest_value)
interest.grid(row=0,column=3)
list_price = StringVar()
list = Entry(window, textvariable=list_price)
list.grid(row=1,column=3)
downpayment_percentage = StringVar()
downpayment = Entry(window, textvariable=downpayment_percentage)
downpayment.grid(row=2,column=3)
#Create button for creating number of grids based on the number of installments.
b1 = Button(window, text="Create", command=create)
b1.grid(row=0,column=4)
#Labels for the enrty boxes
n_installments = Label(window,text="Number Of Installments",foreground="blue")
n_installments.grid(row=3,column=2)
yearly_interest = Label(window,text="Yearly Interest",foreground="blue")
yearly_interest.grid(row=0,column=2)
price_list = Label(window,text="List Price",foreground="blue")
price_list.grid(row=1,column=2)
per_downpayment = Label(window,text="Downpayment Percentage",foreground="blue")
per_downpayment.grid(row=2,column=2)
#Label and text box for the downpayment
t0 = Label(window,text="Downpayment",foreground="green")
t0.grid(row=1,column=0)
t0 = Text(window, height=1, width=20, foreground="red")
t0.grid(row=1,column=1)
window.mainloop()
When you call the NPV_calculation function, ttt is the last text widget.
# This part asks the number of installments and creates the desired amount of text boxes.
def create():
for y in range(number_of_installments.get()):
t11 = Label(window,text= '%s.Installment'%(y+1),foreground="green")
t11.grid(row = y+2,column=0)
for y in range(number_of_installments.get()):
ttt = Text(window, height=1, width=20, foreground="red")
ttt.grid(row = y+2,column=1)
print("the object named ttt in this loop iteration is:", ttt)
#Net present values of the installments are calculated in this part.
def NPV_calculation():
interest_rate = [pow(1+0.0125,i) for i in range(1,int(number_of_installments.get())+1)]
installment_amount = (float(list_price.get())-(float(list_price.get())*float(downpayment_percentage.get())))/(float(number_of_installments.get()))
calculation = [installment_amount/i for i in interest_rate]
ttt.insert(END,calculation)
print("the object named ttt is:", ttt)
downpayment_calculation()
NPV_calculation() # <- when you call this function, ttt is the last Text widget
Output for number_of_installments = 3:
the object named ttt in this loop iteration is: .!text2
the object named ttt in this loop iteration is: .!text3
the object named ttt in this loop iteration is: .!text4
the object named ttt is: .!text4
You need to insert values when creating a text widget in a loop. It is better to move the NPV_calculation function out of the loop.
This is a simplified example for the part where the values are generated automatically.
import tkinter as tk
window = tk.Tk()
def do_n_calculation(n):
calculation = [x+1 for x in range(n)]
return calculation
def create():
# get new values
n = number_of_installments.get()
calculation_list = do_n_calculation(n)
# clear previous values
for i in installment_frame.winfo_children():
i.destroy()
# insert new values
for y in range(n):
t11 = tk.Label(installment_frame, text= '%s.Installment'%(y+1), foreground="green")
t11.grid(row=y, column=0)
for y in range(n):
ttt = tk.Text(installment_frame, height=1, width=20, foreground="red")
ttt.grid(row=y, column=1)
ttt.insert(tk.END, calculation_list[y])
label = tk.Label(window, text="Number Of Installments")
label.grid(row=0, column=0)
number_of_installments = tk.IntVar(value="")
entry = tk.Entry(window, textvariable=number_of_installments)
entry.grid(row=0, column=1)
button = tk.Button(window, text="Create", command=create)
button.grid(row=0, column=2)
installment_frame = tk.Frame(window)
installment_frame.grid(row=1, column=0)
window.mainloop()
Complete example using the class.
import tkinter as tk
class Application(tk.Frame):
"""
| column 0 | column 1 |
-----------------------------------------
row 0 | downpayment_frame | form_frame |
-----------------------------------------
row 1 | installment_frame | |
-----------------------------------------
"""
def __init__(self, master):
super().__init__(master)
# data attributes
self.downpayment_value = None
self.calculation_list = None
# left side
# Label and text box for the downpayment
self.downpayment_frame = tk.Frame(self)
self.downpayment_frame.grid(row=0, column=0, padx=5, pady=5)
self.downpayment_label = tk.Label(self.downpayment_frame, text="Downpayment", foreground="green")
self.downpayment_label.grid(row=0, column=0)
self.downpayment_text = tk.Text(self.downpayment_frame, height=1, width=20, foreground="red")
self.downpayment_text.grid(row=0, column=1)
self.installment_frame = tk.Frame(self)
self.installment_frame.grid(row=1, column=0, padx=5, pady=5)
# right side
self.form_frame = tk.Frame(self)
self.form_frame.grid(row=0, column=1, padx=5, pady=5)
# Labels for the enrty boxes
self.yearly_interest = tk.Label(self.form_frame, text="Yearly Interest", foreground="blue")
self.yearly_interest.grid(row=0, column=0)
self.price_list = tk.Label(self.form_frame, text="List Price", foreground="blue")
self.price_list.grid(row=1, column=0)
self.per_downpayment = tk.Label(self.form_frame, text="Downpayment Percentage", foreground="blue")
self.per_downpayment.grid(row=2, column=0)
self.n_installments = tk.Label(self.form_frame, text="Number Of Installments", foreground="blue")
self.n_installments.grid(row=3, column=0)
# Entry boxes
self.interest_value = tk.StringVar()
self.interest = tk.Entry(self.form_frame, textvariable=self.interest_value)
self.interest.grid(row=0, column=1)
self.list_price = tk.StringVar()
self.price = tk.Entry(self.form_frame, textvariable=self.list_price)
self.price.grid(row=1, column=1)
self.downpayment_percentage = tk.StringVar()
self.downpayment = tk.Entry(self.form_frame, textvariable=self.downpayment_percentage)
self.downpayment.grid(row=2, column=1)
self.number_of_installments = tk.IntVar(value="")
self.installment = tk.Entry(self.form_frame, textvariable=self.number_of_installments)
self.installment.grid(row=3, column=1)
# Create button for creating number of grids based on the number of installments.
self.create_button = tk.Button(self.form_frame, text="Create", command=self.create)
self.create_button.grid(row=0, column=2, rowspan=4, padx=[5, 0])
# Net present values of the installments are calculated in this part.
def NPV_calculation(self, number, list_price, percentage):
interest_rate = [pow(1+0.0125,i) for i in range(1,int(number)+1)]
installment_amount = (float(list_price)-(float(list_price)*float(percentage)))/(float(number))
calculation = [installment_amount/i for i in interest_rate]
return calculation
def downpayment_calculation(self, list_price, percentage):
downpayment = float(list_price)*float(percentage)
return downpayment
def create(self):
number = self.number_of_installments.get()
list_price = self.list_price.get()
percentage = self.downpayment_percentage.get()
# get new values and set data attributes
self.downpayment_value = self.downpayment_calculation(list_price, percentage)
self.calculation_list = self.NPV_calculation(number, list_price, percentage)
# clear previous values
self.downpayment_text.delete("1.0", tk.END)
for i in self.installment_frame.winfo_children():
i.destroy()
# insert new values
self.downpayment_text.insert(tk.END, self.downpayment_value)
for y in range(number):
label = tk.Label(self.installment_frame,text= '%s.Installment'%(y+1), foreground="green")
label.grid(row=y, column=0)
for y in range(number):
text = tk.Text(self.installment_frame, height=1, width=20, foreground="red")
text.grid(row=y, column=1)
text.insert(tk.END, self.calculation_list[y])
self.get_calculation()
def get_calculation(self):
print(self.downpayment_value)
print(self.calculation_list)
root = tk.Tk()
app = Application(master=root)
app.pack()
app.mainloop()

Tkinter dynamically change a widget position with grid geometry manager

I am currently working on a program where I need to change the position of a widget.
Here is my code:
root = Tk()
frame = Frame(root, bg="black")
label1 = Label(frame, text="not important")
label.grid(row=1, column=1)
#some stuff happens
x = aFunctionThatReturnsXCoordinate #not actual name
y = aFunctionThatReturnsYCoordinate
Now I want to change the position of label1 to the new coordinates.
I have tried:
label1.forget_grid()
label1.grid(rows=x, columns=y)
#Ive tried label1/frame.update after this code but it didnt do anything
I've also tried to do it without the grid_forget.
I didn't forget the frame.pack and root.mainloop.
Is there a function to change the position?
I have made a code which contains a label and a button. When the button is pressed , the row of the label changes from 0 to 1 and when pressed again row is changes from 1 to 0 and so on. To make difference between the frame and the root, I have set the color of the frame to sky blue and that of root to pink.
from tkinter import *
global rw;rw = 0
def changed():
global rw;rw += 1;
if rw == 2:rw=0
label.grid(row=rw,column=0)
root = Tk()
root.config(bg="pink")
frame = Frame(root, bg="sky blue")
frame.pack()
label = Label(frame,text="Hello")
label.grid(row=0,column=0)
b = Button(frame, text='Press me!', command=changed)
b.grid(row=0, column=1)
root.mainloop()
Well, the above code is a bit complicated so , if you want a simpler way to do the same:
from tkinter import *
def changed():
size = label.grid_info().get("row") #getting current row
if size == 0:size = 1
elif size == 1:size = 0
label.grid(row=size,column=0)
root = Tk()
root.config(bg="pink")
frame = Frame(root, bg="sky blue")
frame.pack()
label = Label(frame,text="Hello")
label.grid(row=0,column=0)
b = Button(frame, text='Press me!', command=changed)
b.grid(row=0, column=1)
root.mainloop()
Here is an animation:
Here is an example that toggles the position of a label from column 0 to column 1:
You have to keep in mind that unoccupied rows or columns are sized at zero pixels by the grid geometry manager.
pressing the button makes the label in row 1 swap places from column 0 to 1 and vice versa.
import tkinter as tk
def move_label(ndx=[0]):
# the 3 next toggle the column value
rowcol = [(1, 1), (1, 0)]
x, y = rowcol[ndx[0]]
ndx[0] = (ndx[0] + 1) % 2
label_at_1_0.grid(row=x, column=y)
root = tk.Tk()
frame = tk.Frame(root, bg="black")
frame.pack()
label_at_0_0 = tk.Label(frame, text="label_at_0_0")
label_at_0_0.grid(row=0, column=0)
label_at_0_1 = tk.Label(frame, text="not label_at_0_1")
label_at_0_1.grid(row=0, column=1)
label_at_1_0 = tk.Label(frame, text="label_at_1_0")
label_at_1_0.grid(row=1, column=0)
btn_to_move_label = tk.Button(frame, text='move label', command=move_label)
btn_to_move_label.grid(row=1, column=3)
root.mainloop()

How can I dynamically create ttk widgets depending on the value entered in a ttk.entry box?

I am trying to make a GUI where as soon as the user inputs an integer into a ttk.entry field, that many checkbuttons need to appear below it. For example, if they put "5" into the entry widget, 5 check buttons need to appear below the entry field.
Edit:
What I ended up using:
self.number_of_stages = tk.IntVar()
self.check_box_dict={}
self.num_of_stages={}
self.stagetempvar={}
self.equipment_widgets={}
def centrifugal_compressor_widgets(self):
self.equipment_widgets.clear()
self.equipment_widgets["NumOfStagesLabelCentComp"]=tk.Label(self.parent, text="Number of Stages:", bg="white")
self.equipment_widgets["NumOfStagesLabelCentComp"].place(relx=0.5, y=260, anchor="center")
self.equipment_widgets["NumOfStagesEntryCentComp"]=ttk.Entry(self.parent, textvariable=self.number_of_stages)
self.equipment_widgets["NumOfStagesEntryCentComp"].place(relx=0.5, y=290, anchor="center")
def OnTraceCentComp(self, varname, elementname, mode):
for key in self.check_box_dict:
self.check_box_dict[key].destroy()
try:
if self.number_of_stages.get() <=15 :
i=1
self.stagetempvar.clear()
while i <= self.number_of_stages.get():
self.stagetempvar[i]=tk.StringVar()
self.stagetempvar[i].set("Closed")
self.check_box_dict[i]=ttk.Checkbutton(self.parent, text=i, offvalue="Closed", onvalue="Open",variable=self.stagetempvar[i])
self.check_box_dict[i].place(relx=(i*(1/(self.number_of_stages.get()+1))), y=360, anchor="center")
i+=1
except:
pass
take a look at the below and let me know what you think...
A very ugly, super basic example:
from Tkinter import *
root = Tk()
root.geometry('200x200')
root.grid_rowconfigure(0, weight = 1)
root.grid_columnconfigure(0, weight = 1)
win1 = Frame(root, bg= 'blue')
win1.grid(row=0, column=0, sticky='news')
number = IntVar()
entry = Entry(win1, textvariable = number)
entry.pack()
confirm = Button(win1, text = 'Press to create widgets...', command = lambda:create_widgets(number.get()))
confirm.pack()
def create_widgets(number):
for n in range(0,number):
Checkbutton(win1, text = 'Checkbutton number : %s' % n).pack()
root.mainloop()

Why the text is not displayed on the label?

I see the text if I enlarge the window manually, so the text is there! (On the label) but if not enlarged the window I can not see, I see only a piece of the label
How can I fix it? Do I have to resize?
I've tried changing the font size, the size of the label and some other things and I could not even solve the problem.
This is the code:
from Tkinter import *
import ttk
import time
import threading
def start():
start_stop.config(text="QUIT", command=stop, image=photo2)
thread = threading.Thread(target=progBar, args=())
thread.daemon = True
thread.start()
def progBar():
for i in xrange(300):
if i < 50:
lbl1.config(height=0, width=4, font=('times', 400, 'bold'),
text="AAAA!!")
lbl1.config(fg='black')
if i % 5:
lbl1.config(bg='white')
else:
lbl1.config(bg='red')
if i == 50:
lbl1.destroy()
if i >= 200:
s = ttk.Style()
s.theme_use('clam')
if i % 5:
s.configure("red.Horizontal.TProgressbar",
foreground='#205F8C', background='#205F8C')
else:
s.configure("red.Horizontal.TProgressbar",
foreground='red', background='red')
pbar_det.config(style="red.Horizontal.TProgressbar")
pbar_det.step(0.33)
master.update()
# Busy-wait
time.sleep(0.1)
master.destroy()
def stop():
master.destroy()
master = Tk()
photo1 = PhotoImage(file="Press1.gif")
photo2 = PhotoImage(file="Press2.gif")
ws = master.winfo_screenwidth() # width of the screen
hs = master.winfo_screenheight() # height of the screen
width = ws
height = 120
x = ws-width # Window's coords
y = hs-height
start_stop = Button(master, text='START', command=start, image=photo1)
start_stop.grid(row=0, column=1, pady=2, padx=2, sticky=E+W+N+S)
pbar_det = ttk.Progressbar(master, orient="horizontal", length=ws-450,
mode="determinate")
pbar_det.grid(row=0, column=0, pady=2, padx=2, sticky=E+W+N+S)
lbl1 = Label(master)
lbl1.grid(row=0, column=1, pady=2, padx=2)
lbl2 = Label(master)
lbl2.grid(row=0, column=1, pady=2, padx=2)
master.geometry('%dx%d+%d+%d' % (width, height, x, y))
master.mainloop()
Try anchoring the text within the label to the left.
lbl1.config(anchor="nw") # nw = north-west = top left
I see at least four problems in the code:
you are forcing the size of the widget to a specific height when you call master.geometry(...). This prevents the window from growing or shrinking to fit the internal widgets
you are specifying a really huge font (400 points) which can't fit in the height you've picked. Because of the huge size of the font relative to the space you've given it (by explicitly setting the height of the window) what you see is the natural whitespace above the letters that is present in all fonts).
you are putting two labels and one button on top of each other in the same row and column
you are using threading. Tkinter isn't thread safe. Your code might work, but it might not.
If you remove the call to master.geometry(), the window will expand to fit the height of the text. Or, you can not make the font so huge.

Unable to achieve wanted entry textBox alignment

HI i am trying to place the alignment of my Entry(Text Box) according to the image below. I tried everything, TOP BOTTOM LEFT RIGHT.
This is the alignment i want. Obtained from paint program*
Problem
Coding of tkinter
master = Tk.Tk() # Open up GUI connection
master.title('Program Application')
print "VSM activated input range first (X2 must be larger than X1)"
#Declare button and respective method
button = Tk.Button(text='VSM', command=VSM, fg="red")
button.config( height = 10, width = 80 )
button.pack() #pack is needed to display the button
bluebutton = Tk.Button(text="AGM Folder",command= lambda: Folder(0), fg="blue").pack(side = LEFT)
bluebutton = Tk.Button(text="VSM Folder",command= lambda: Folder(1), fg="blue").pack(side = RIGHT)
Label(text='Correct Range for Gradient\nX2 X1').pack(side=TOP,padx=10,pady=10)
entryX2 = Entry(master, width=10)
entryX2.pack(side=LEFT,padx=10,pady=10)
entryX1 = Entry(master,width=10)
entryX1.pack(side=RIGHT,padx=10,pady=10)
buttonGradient = Tk.Button(text='Input Range OP',command= lambda: Folder(2), fg="red").pack()
entryX2IP = Entry(master, width=10)
entryX2IP.pack(side=LEFT,padx=10,pady=10)
entryX1IP = Entry(master,width=10)
entryX1IP.pack(side=RIGHT,padx=10,pady=10)
btnGradientIP = Tk.Button(text='Input Range IP',command= lambda: Folder(2), fg="red").pack(side = TOP)
master.mainloop() # Continue loop till user close tab
Use Frame:
master = Tk.Tk() # Open up GUI connection
master.title('Program Application')
print "VSM activated input range first (X2 must be larger than X1)"
#Declare button and respective method
button = Tk.Button(text='VSM', command=VSM, fg="red")
button.config( height = 10, width = 80 )
button.pack() #pack is needed to display the button
bluebutton = Tk.Button(text="AGM Folder",command= lambda: Folder(0), fg="blue").pack(side = LEFT)
bluebutton = Tk.Button(text="VSM Folder",command= lambda: Folder(1), fg="blue").pack(side = RIGHT)
Label(text='Correct Range for Gradient\nX2 X1').pack(side=TOP,padx=10,pady=10)
################### Use 3 frames to contains entries, buttons.
frameX2 = Frame(master)
frameX2.pack(side=LEFT, expand=1, anchor=E)
entryX2 = Entry(frameX2, width=10)
entryX2.pack(side=TOP,padx=10,pady=10)
entryX2IP = Entry(frameX2, width=10)
entryX2IP.pack(side=TOP,padx=10,pady=10)
frameButton = Frame(master)
frameButton.pack(side=LEFT)
Tk.Button(frameButton, text='Input Range OP',command= lambda: Folder(2), fg="red").pack(padx=10, pady=10)
Tk.Button(frameButton, text='Input Range IP',command= lambda: Folder(2), fg="red").pack(padx=10, pady=10)
frameX1 = Frame(master)
frameX1.pack(side=LEFT, expand=1, anchor=W)
entryX1 = Entry(frameX1,width=10)
entryX1.pack(side=TOP,padx=10,pady=10)
entryX1IP = Entry(frameX1,width=10)
entryX1IP.pack(side=TOP,padx=10,pady=10)
#####################
master.mainloop() # Continue loop till user close tab

Categories