How can i fix this Textwidget in Tkinter? - python

Why is y not output twice if you type 2 in the text field?
Thanks for help
from tkinter import *
root = Tk()
root.geometry("500x450")
def copy():
y = txt.get(1.0, END)
print(y)
if y == "2":
print("Check")
txt = Text(root, width=60, height=20, font=("Arial", 12))
txt.place(x=0, y=0)
btn = Button(root, text="Copy", command=copy)
btn.place(x=250, y=400)
mainloop()

because there is a hidden \n here. If you change your if to if y == "2\n": it will print check

Related

How can i change content inside of a window after pressing a button in tkinter?

I actually found a solution for this but they used an entirely different way of making windows/buttons and i can't figure out how to use it.
Please tell me if there's a way to make this happen with my code.
The code for my window and its content is as below
from tkinter import *
title = 'zromber'
window = Tk()
window.geometry("800x400")
def play():
print('welcome')
window.destroy()
def save():
print('yes')
playbutton = Button(window, text='play')
playbutton.config(command=play)
playbutton.config(font=('none', 50, 'bold'))
testlabel = Label(window, text=title)
testlabel.config(font=('Ink Free', 50))
testlabel.pack()
playbutton.pack()
savebutton = Button(window, text='save')
savebutton.config(command=save)
savebutton.config(font=('none', 50, 'bold'))
savebutton.pack()
window.mainloop()
from tkinter import *
title = 'zromber'
window = Tk()
window.geometry("800x400")
my_text = "Hi, I'm a the new label"
def play():
#use label.config(text="new text") to change text
my_label.config(text=my_text+" and I'm from play")
def save():
my_label.config(text=my_text+" and I'm from save")
playbutton = Button(window, text='play')
playbutton.config(command=play)
playbutton.config(font=('none', 50, 'bold'))
testlabel = Label(window, text=title)
testlabel.config(font=('Ink Free', 50))
testlabel.pack()
playbutton.pack()
savebutton = Button(window, text='save')
savebutton.config(command=save)
savebutton.config(font=('none', 50, 'bold'))
savebutton. pack()
#Define the label
my_label = Label(window, text="THIS IS A LABEL")
my_label.config(font=('none', 10, 'bold'))
my_label.pack()
window.mainloop()
Here I've created a new label called my_label and when the play button calls for the play() function, i've used label.config(text="new text") to change text.
You can run the sample code above to get your results.

Values not stored in Tkinter Variables

In my code, I have tried to get the user input through text fields, store them in variables and finally print them in a tabular form.
The problem I am facing is that none of the values I enter through the text fields get displayed; when I try printing the variables, they come up empty.
Here's part of my code:
# SPASC
from tkinter import *
import tkinter as tk
import tkinter.ttk as tktrv
root = tk.Tk()
root.title("SPASC")
root.geometry("410x400")
lb1 = Label(root, text="SPASC \n Welcomes You !!!", fg="red", bg="sky blue"
, font=('Arial Black', 20), width=22, anchor=CENTER)
lb2 = Label(root, text="What would you like to compare?",
font=('Arial', 18), anchor=CENTER)
space1 = Label(root, text="\n\n")
lb1.grid(row=0)
lb2.grid(row=5)
space1.grid(row=1)
hpw, mil = StringVar(), StringVar()
def bt_cars():
w1 = Toplevel()
w1.title("Choose Features")
w1.geometry("430x200")
lb3 = Label(w1, text="Choose features for comparison", bg="yellow"
, font=('Arial Black', 18), width=25)
lb4 = Label(w1, text=" ", anchor=CENTER)
fr1 = LabelFrame(w1, width=20, padx=100)
hpw_cb = Checkbutton(fr1, text="Horsepower", variable=hpw, anchor='w', onvalue="Horsepower", offvalue="")
hpw_cb.grid()
hpw_cb.deselect()
mil_cb = Checkbutton(fr1, text="Mileage", variable=mil, anchor='w', onvalue="Mileage", offvalue="")
mil_cb.grid()
mil_cb.deselect()
var_stor = [hpw, mil]
print(hpw)
print(mil)
var_fill = []
for itr1 in var_stor:
if itr1 != "":
var_fill.append(itr1)
print(var_fill)
def car_1():
name1 = StringVar()
c1 = Toplevel()
c1.title("Car 1")
c1.geometry("430x200")
car1_lb1 = Label(c1, text="Car Name:")
name1_ifl = Entry(c1)
name1 = name1_ifl.get()
elm_var_fill = len(var_fill)
ct1 = 0
car1_val = []
for itr2 in var_fill:
if ct1 == elm_var_fill:
break
lb5 = Label(c1, text=itr2.get())
#Creating text field
ftr1_ifl = Entry(c1)
car1_ftr = ftr1_ifl.get()
car1_val.append(car1_ftr)
car1_ftr = None
lb5.grid(row=ct1 + 2, column=1)
ftr1_ifl.grid(row=ct1 + 2, column=2)
ct1 += 1
print(car1_val)
def display():
dp = Toplevel()
dp.title("Results")
dp.geometry("500x200")
car1_pt = 0
car2_pt = 0
car_tree = tktrv.Treeview(dp)
car_tree["columns"] = ("car1col")
car_tree.column("#0", width=120, minwidth=30)
car_tree.column("car1col", width=120, minwidth=30)
car_tree.heading("#0", text="Features" )
car_tree.heading("car1col", text=str(name1))
car_tree.pack()
c1.withdraw()
print(var_fill)
done1_bt = Button(c1, text="Continue", command=display)
name1_ifl.grid(row=0, column=2)
car1_lb1.grid(row=0, column=1)
done1_bt.grid(row=5,column=1)
w1.withdraw()
done_bt = Button(w1, text="Done", command=car_1)
done_bt.grid(row=3, column=1)
lb3.grid(row=0, column=1)
lb4.grid(row=1, column=1)
fr1.grid(row=2, column=1)
root.withdraw()
bt1 = Button(root, text="CARS", width=5, font=('Calibri', 15), command=bt_cars)
bt1.grid(row=7)
space2 = Label(root, text="\n\n")
space2.grid(row=6)
root.mainloop()
I am facing trouble with the variables named: hpw, mil, name1.
Any help would be welcome.
NOTE:- Please excuse the amount of code; I wanted others to replicate the error and see it for themselves
For the variables hpw and mil, these variables are empty strings that's why you are not getting any value from those checkboxes. To get values from the checkboxes replace these lines of code:
var_stor = [hpw, mil]
with
var_stor = [hpw_cb.cget('onvalue'), mil_cb.cget('onvalue')]
since you want the onvalue then you must use cget() method to access those values.
also, replace
lb5 = Label(c1, text=itr2.get())
with
lb5 = Label(c1, text=itr2)
because now you have required values (not objects) in a list, so just need to access those values.
For the variable name1 you can use #BokiX's method.
The problem is you are using get() wrong. You cannot use get() right after Entry() because as soon as entry is created it's getting the input before the user can even input something.
Use this code:
def get_input(text):
print(text)
e = Entry(root)
e.pack()
b = Button(root, text="Print input", command=lambda: get_input(e.get()))
b.pack()
Now get() method will not be executed before you click the button.

Destroying a label in Tk

I've wracked my brain about this. I'm new to Python and Tk,and just trying it out. I would think this would be really easy, but I can't get it. Here's my code:
from tkinter import *
window = Tk()
window.geometry = ('400x200')
mylabel = Label(window)
def button_command():
Label(window).destroy()
text = entry1.get()
selection=variable.get()
if selection == "Celsius":
f = "Fahrenheit: " + str(round((int(text) - 32) * 5/9,2))
mylabel = Label(window, text = f).pack()
else:
c = "Celsuius: " + str(round((int(int(text)) * 9/5) + 32))
mylabel = Label(window, text = c).pack()
return None
def clear_label():
mylabel.destroy()
entry1 = Entry(window, width = 20)
entry1.pack()
variable = StringVar(window)
variable.set("Fahrenheit") # default value
w = OptionMenu(window, variable, "Fahrenheit", "Celsius")
w.pack()
Button(window, text="Button", command=button_command).pack()
Button(window, text="Clear", command=clear_label).pack()
window.mainloop()
I don't get an error, but the clear_label function doesn't do anything. It doesn't return an error. It just doesn't work. Any suggestions would be appreciated. :)
You never actually packed the label into the window, therefore there was nothing to destroy. If you run this code, you can see that once packed, your function works as expected.
from tkinter import *
window = Tk()
window.geometry = ('400x200')
mylabel = Label(window, text="test")
def button_command():
Label(window).destroy()
text = entry1.get()
selection=variable.get()
if selection == "Celsius":
f = "Fahrenheit: " + str(round((int(text) - 32) * 5/9,2))
mylabel = Label(window, text = f).pack()
else:
c = "Celsuius: " + str(round((int(int(text)) * 9/5) + 32))
mylabel = Label(window, text = c).pack()
return None
def clear_label():
mylabel.destroy()
mylabel.pack
entry1 = Entry(window, width = 20)
entry1.pack()
variable = StringVar(window)
variable.set("Fahrenheit") # default value
w = OptionMenu(window, variable, "Fahrenheit", "Celsius")
mylabel.pack()
Button(window, text="Button", command=button_command).pack()
Button(window, text="Clear", command=clear_label).pack()
window.mainloop()
Not sure whether the aim of the exercise is to destroy a label or just clear the label and give it a new value. If it is the latter, it can be achieved using the text variable parameter to label.
from tkinter import *
def button_command():
text = entry1.get()
selection=variable.get()
# Change the value of the stringvar to set the new value
if selection == "Celsius":
labelvalue.set("Fahrenheit: " + str(round((int(text) - 32) * 5/9,2)))
else:
labelvalue.set("Celsuius: " + str(round((int(int(text)) * 9/5) + 32)))
return None
def clear_label():
# No need to destroy - just change the value
labelvalue.set("")
window = Tk()
window.geometry = ('400x200')
entry1 = Entry(window, width = 20)
entry1.pack()
variable = StringVar(window)
variable.set("Fahrenheit") # default value
w = OptionMenu(window, variable, "Fahrenheit", "Celsius")
w.pack()
Button(window, text="Button", command=button_command).pack()
Button(window, text="Clear", command=clear_label).pack()
# The text displayed in mylabel will be the contents of labelvalue
labelvalue = StringVar()
mylabel = Label(window, textvariable=labelvalue)
mylabel.pack()
window.mainloop()
In principle, you don't have to delete and re-create the Label, just clear the fields in the Label and in the Entry:
def clear_label():
mylabel.config(text="")
entry1.delete(0, 'end')

Why my code doesn't execute and how can I execute it?

It got executed once but I add some features and now it doesn't work anymore...
I'm a beginner at python and this is my first project. I'd like to create a game (which works perfectly in the console) but I have some troubles to put it with tkinter
If someone could take a look at this, it would be nice, thanks
Here's my code, I might have mistyped something or I don't know but I'm stucked with this and I can't find the mistake.
import tkinter as tk
from tkinter import Tk, Label, Canvas, Button, Frame, Toplevel, Entry
from random import randrange
num = randrange(0, 50)
money = 100
root = Tk()
root.geometry("750x750")
root["bg"]="beige"
label = Label(root, text="Welcome to the Casino")
label.place(width=180, x=300, y=300)
def csn(x, y, z, i):
if y < 50 and y >= 0 and z <= i :
if y == x:
i += z * 3
return "Well guess. You have %d" %(i)
elif (x % 2 == 0 and y % 2 == 0) or ( x % 2 != 0 and y % 2 != 0):
i += z * 0.5
return "Not so ba. You have %d" %(i)
else:
i -= z
return "Oops, Try again, you loose %d. You now have %d" %(z, i)
else:
return "Try again..."
def submit(master):
label1 = Label(master, text="try again...")
label1.place(width=180, x=300, y=300)
def casino():
top = Toplevel()
top['bg']= 'blue'
top.geometry = ('700x700')
root.withdraw
while money > 0:
try:
number_label = Label(top, text="Chose a nombre : ")
number_label.place(width=180, x=100, y=300)
nentry= Entry(top)
nentry.place(width=180, x=200, y=300)
number = int(nentry.get())
mise_label = Label(top, text="Entre the price you want to mise : ")
mise_label.place(width=180, x=100, y=400)
mise_entry = Entry(top)
mise_entry.place(width=180, x=200, y=400)
mise = float(mise_entry.get())
except ValueError:
btn3 = Button(top, text="submit", command=lambda : submit(top))
btn3.place(width=180, x=300, y=300)
btn = Button(top, text="submit", command= lambda : csn(num, number, mise, money))
btn.place(width=180, x=300, y=500)
else:
label2= Label(top, text="you lose")
label2.place(width=180, x=300, y=500)
btn1 = Button(top, text="Quit", command=top.quit)
btn1.place(width=180, x=300, y=400)
btn2 = Button(top, text="try again", command=casino)
btn2.place(width=180, x=200, y=400)
enter code here
button = Button(root, text="play!", relief='groove', command=casino)
button.place(width=180, x=300, y=400)
root.mainloop()

Python - Tkinter - Label Not Updating

Any ideas why the leftresult_label label does not update? The function seems to work but the label does not update. I have looked everywhere and can't find an answer. The 'left' value gets set but the label does not change.
from tkinter import *
root = Tk(className="Page Calculator")
read = IntVar()
total = IntVar()
left = IntVar()
read.set(1)
total.set(1)
left.set(1)
read_label = Label(root,text="Pages Read:")
read_label.grid(column=1, row=1)
total_label = Label(root,text="Total Pages:")
total_label.grid(column=1, row=2)
read_entry = Entry(root,textvariable=read)
read_entry.grid(column=2, row=1)
total_entry = Entry(root,textvariable=total)
total_entry.grid(column=2, row=2)
def func1():
left.set(total.get() - read.get())
print(left.get())
calculate_button = Button(root,text="Calculate",command= func1)
calculate_button.grid(column=2, row=3)
percenet_label = Label(root,text="Percent Finished:")
percenet_label.grid(column=1, row=4)
left_label = Label(root,text="Pages Left:")
left_label.grid(column=1, row=5)
percenetresult_label = Label(root,text=left.get())
percenetresult_label.grid(column=2, row=4)
leftresult_label = Label(root,text="")
leftresult_label.grid(column=2, row=5)
root.mainloop()
To make the function do the job, you'd rather have your label:
leftresult_label = Label(root, textvariable=left)
Once it's tkinter class variable, tkinter takes care about when you change the value. Once you click the button,
def func1():
left.set(total.get() - read.get())
percent.set(int(read.get()*100/total.get()))
left and percent values, which are instances of tkinter.IntVar() class have immidiate effect on widgets (labels in this case) where those values are set as textvariable, just as you have it at Entry widgets.
Here is full code:
from tkinter import *
root = Tk(className="Page Calculator")
read = IntVar()
total = IntVar()
left = IntVar()
percent = IntVar()
read.set(1)
total.set(1)
left.set(1)
percent.set(1)
def func1():
left.set(total.get() - read.get())
percent.set(int(read.get()*100/total.get()))
read_label = Label(root,text="Pages Read:")
read_label.grid(column=1, row=1)
read_entry = Entry(root,textvariable=read)
read_entry.grid(column=2, row=1)
total_label = Label(root,text="Total Pages:")
total_label.grid(column=1, row=2)
total_entry = Entry(root,textvariable=total)
total_entry.grid(column=2, row=2)
calculate_button = Button(root,text="Calculate",command= func1)
calculate_button.grid(column=2, row=3)
percenet_label = Label(root,text="Percent Finished:")
percenet_label.grid(column=1, row=4)
left_label = Label(root,text="Pages Left:")
left_label.grid(column=1, row=5)
percenetresult_label = Label(root,textvariable=percent)
percenetresult_label.grid(column=2, row=4)
leftresult_label = Label(root,textvariable=left)
leftresult_label.grid(column=2, row=5)
root.mainloop()
code including progress bar. update_idletasks() used to keep label and progress bar running.
from tkinter import *
from tkinter import ttk
root = Tk()
root.title('Counter Test')
root.iconbitmap('IT.ico')
root.geometry("800x400")
def missing():
while i < 100:
progress1['value'] = i
label1.config(text=progress1['value'])
root.update_idletasks()
i += 1
progress1 = ttk.Progressbar(root, orient=HORIZONTAL, length=250, mode='determinate')
progress1.pack(pady=15)
label1 = Label(root, text="")
label1.pack(pady=15)
button_1 = Button(root, text="Missing", command=missing)
button_1.pack(pady=15)
button_q = Button(root, text="Quit", command=root.destroy)
button_q.pack(pady=15)
root.mainloop()
so to update controls immediately, like updating labels and TreeView elements this code worked for me.
window = tk.Tk()
window.update_idletasks()

Categories

Resources