Can anyone tell me how to make if statement if the text of button is equal example like this code
from tkinter import *
app = Tk()
def k():
#i know this is wrong so plss correct me
if button1.text == "1":
l = Label(app,text="wow")
l.pack
button1 = Button(app,text="1",command=k).pack()
app.mainloop()
Plss tell me thank you
Since the object of tkinter consists of a dictionary, you can get a value by accessing the key value 'text'.
from tkinter import *
app = Tk()
def k():
if button1["text"] == "1":
l = Label(app,text="wow")
l.pack()
button1 = Button(app,text="1",command=k)
button1.pack()
app.mainloop()
Related
when I run this code for **Exemple ** then I click on the ttk entry and press enter it print ----> "ttk_entry"
But when I do the same thing to the customtkinter.CTkEntry it print **nothing **.
import customtkinter
from tkinter import *
def test(event):
if root.focus_get() == custom_entry:
print("custom_entry")
elif root.focus_get() == ttk_entry:
print("ttk_entry")
root = customtkinter.CTk()
custom_entry = customtkinter.CTkEntry(root) #CTkEntry
custom_entry.pack()
ttk_entry = Entry(root) #ttk_entry
ttk_entry.pack()
root.bind("<Return>", test)
root.mainloop()
I was expecting that it print "custom_entry" .
I have a database that includes students' information. In the middle of the program, I need a Tkinter window to be open. How should I open a GUI window in the middle of a Python program?!
The window must include a search box (Entry) by n_number (dictionary value) to show the name (dictionary key related to the entered n_number) of the student and a list of all students. At the same time that I can search by n_number, I need the list of all students, so I can click on each name and see the courses he/she got. I don't know how can I make a clickable list in Tkinter.
...
from tkinter import *
class Student:
def __init__(self):
self.name = ""
self.n_number = None
self.courses = {}
self.students = {}
def add_stu(self, name, n_number):
self.students[name] = n_number
def find_stu(self, n_number):
return list(self.students.keys())[list(self.students.values()).index(n_number)]
def add_course(self, cname, score):
self.courses[cname] = score
...
Just .destroy your root element after you get what you want from user, consider following simple example:
from tkinter import *
user_input = ""
def get_and_destroy():
global user_input
user_input = entry.get()
root.destroy()
print("Before tkinter")
root = Tk()
entry = Entry(root)
entry.pack()
btn = Button(root, text="Go", command=get_and_destroy)
btn.pack()
mainloop()
print("After tkinter")
print("User typed:",user_input)
As you might observe destroy-ing cause breaking from mainloop()
Create a function with the Tkinter and call it when you need the pop up.
To start a Tkinter in the middle of a program, you just declare a Tk() and end it with a .mainloop(). This will stop it from continuing until the window is closed:
from tkinter import *
import time
print('hi')
time.sleep(1)
print('Tkinter starting in:')
time.sleep(1)
print('3')
time.sleep(1)
print('2')
time.sleep(1)
print('1')
root = Tk()
# Put GUI elements in here
root.mainloop()
print('WHY DID YOU LEAVE ME')
As for clickable lists, I would suggest looking into ttk and ttk treeview
To add another window you do Tk()
from tkinter import *
wn = Tk()
wn.title('Window 1')
window = Tk()
window.title('Window2')
I'm new to Python and Tkinter and was trying to create an interface to search & plot data. I created a very simple toplevel window to get the values from a combobox that would be selected from users. However, I find the script would only print the first item in the list if comboxlist2.current(0) was set or it would print nothing, no matter which one is selected in the box. I created a sample script to test this. If I click on the "search & create", then the return values can change according to the user selection in comboxlist1, while it would all return "1" no matter what the user selected in comboxlist2. So may I ask where is the issue and how to solve?
Thanks in advance for the potential suggestions or solutions!
import tkinter as tk
from tkinter import ttk
from tkinter import *
def root_print():
reg_in = comboxlist1.get()
print(reg_in) #print the value selected
def on_click():
tl = Toplevel()
comvalue2 = tk.StringVar()
comboxlist2 = ttk.Combobox(tl,textvariable=comvalue2)
comboxlist2["values"] = ("1","2","3")
comboxlist2.grid()
comboxlist2.current(0) #select the first one as default
#mm = comboxlist2.get()
#print(mm) #print directly
go(comboxlist2,tl)
tl.wait_window()
return
def go(comboxlist2,tl):
mm = comboxlist2.get()
Button(tl,text='go', command=lambda:test(mm)).grid()
def test(mm):
print(mm) #do the same thing for the comboxlist2
root = Tk()
root.title('search') #create an interface
root.geometry('+400+200') #size and position
Label(text='region ').grid(row=2,column=0)
comvalue1 = tk.StringVar()
comboxlist1=ttk.Combobox(root,textvariable=comvalue1)
comboxlist1["values"]=("all","africa","asia","australia","canada","europe","mexico","southamerica","usa")
comboxlist1.grid(row=2,column=1)
comboxlist1.current(0)
Button(text='search & create', command=root_print).grid(row=0,column=4)
Button(text='click', command=on_click).grid(row=1, column=4)
loop = mainloop()#go!
Here is the working code, which should take care of your needs. I have removed the imports and some code snippets which are not useful.
import tkinter as tk
from tkinter import ttk
def root_print():
reg_in = comboxlist1.get()
print(reg_in)
def on_click():
tl = tk.Toplevel()
comvalue2 = tk.StringVar()
comboxlist2 = ttk.Combobox(tl,textvariable=comvalue2)
comboxlist2["values"] = ("1","2","3")
comboxlist2.grid()
comboxlist2.current(0) #select the first one as default
tk.Button(tl,text='go', command=lambda: test(comboxlist2.get())).grid()
tl.wait_window()
def test(mm):
print(mm)
root = tk.Tk()
root.title('search') #create an interface
root.geometry('+400+200') #size and position
tk.Label(text='region ').grid(row=2,column=0)
comvalue1 = tk.StringVar()
comboxlist1=ttk.Combobox(root,textvariable=comvalue1)
comboxlist1["values"]=("all","africa","asia","australia","canada","europe","mexico","southamerica","usa")
comboxlist1.grid(row=2,column=1)
comboxlist1.current(0)
tk.Button(text='search & create', command=root_print).grid(row=0,column=4)
tk.Button(text='click', command=on_click).grid(row=1, column=4)
root.mainloop()
The following code is runnable, you can just copy/paste:
from tkinter import *
import multiprocessing
startingWin = Tk()
def createClientsWin():
def startProcess():
clientsWin = Tk()
label = Label(clientsWin, text="Nothing to show")
label.grid()
clientsWin.mainloop()
if __name__ == "__main__":
p = multiprocessing.Process(target=startProcess)
p.start()
button = Button(startingWin, text="create clients", command=lambda: createClientsWin())
button.grid()
startingWin.mainloop()
So I simply want to create a completely separated Tk() window using multiprocessing. When I click on the create button, I just get the original window (not the intended one) and it gives me this error:
AttributeError: Can't pickle local object 'createClientsWin.<locals>.startProcess'
*Could someone explain how to start a separate new Tk() window using multiprocessing? *
Update: Not A Duplicate
Even if I follow the solution provided in the possible duplicate question, that doesn't help solving my question. Simply because, Tkinter is being used in my case. The modified code:
def createClientsWin():
clientsWin = Tk()
label = Label(clientsWin, text="Nothing to show")
label.grid()
clientsWin.mainloop()
def createClientsWinProcess():
if __name__ == "__main__":
p = multiprocessing.Process(target=createClientsWin)
p.start()
startingWin = Tk()
button = Button(startingWin, text="create clients", command=lambda: createClientsWinProcess())
button.grid()
startingWin.mainloop()
Function in global scope should be used for multiprocess target function, so the startProcess() should be moved into global scope.
Also the checking of if __name__ == "__main__" inside startProcess() will cause the code inside the if block not being executed.
Finally the creation of startingWin should be put inside if __name__ == "__main__" block, otherwise every process started will create the startingWin.
Below is the proposed changes to solve the above issues:
from tkinter import *
import multiprocessing
def startProcess():
clientsWin = Tk()
label = Label(clientsWin, text="Nothing to show")
label.grid()
clientsWin.mainloop()
def createClientsWin():
p = multiprocessing.Process(target=startProcess)
p.start()
if __name__ == '__main__':
startingWin = Tk()
button = Button(startingWin, text="create clients", command=createClientsWin)
button.grid()
startingWin.mainloop()
It is easier to use classes when using multiprocessing with tkinter. Try the following code:
import tkinter as Tk
import multiprocessing as mp
class A:
def __init__(self, master):
self.master = master
label = Tk.Label(self.master, text = 'A')
label.pack()
root_b = Tk.Toplevel()
GUI_B = B(root_b)
mp.Process(target = GUI_B.mainloop())
def mainloop(self):
self.master.mainloop()
class B:
def __init__(self, master):
self.master = master
label = Tk.Label(self.master, text = 'B')
label.pack()
def mainloop(self):
self.master.mainloop()
if __name__=='__main__':
root = Tk.Tk()
GUI_A = A(root)
mp.Process(target = GUI_A.mainloop())
I want to build a calculator using tkinter, I am just a beginner.
I think the problem is in the '=' button, it just doesn't work and I can't figure out why.for now i just want button from 1 to 9, plus, minus and equals buttons.when i press a number is display it in the entry but the equals button isnt working. for example if i want to do 1+2, it will show 1 and ill press the plus button then 2 and in the entry ill still see 2 instead of 3
from Tkinter import *
import math
class Calc():
def __init__(self):
self.total=0
self.current=""
self.new_num=True
self.op_pending=False
self.op=""
self.eq=False
def num_press(self,num):
self.eq=False
temp=e.get()
temp2=str(num)
if self.new_num:
self.current=temp2
self.new_num=False
else:
if temp2=='.':
if temp2 in temp:
return
self.current=temp+temp2
self.display(self.current)
def calc_total(self):
self.eq=True
self.current=float(self.current)
if self.op_pending==True:
self.do_sum()
else:
self.total=float(e.get())
def display(self,value):
e.delete(0,END)
e.insert(0,value)
def do_sum(self):
if self.op=="add":
self.total+=self.current
if self.op=="minus":
self.total-=self.current
self.new_num=True
self.op_pending=False
self.display(self.total)
def operation(self,op):
self.current=float(self.current)
if self.op_pending:
self.do_sum()
elif not self.eq:
self.total=self.current
self.new_num=True
self.op_pending=True
self.op=op
self.eq=False
def clear(self):
self.total=0
sum=Calc()
root=Tk()
root.geometry("345x270+200+200")
e = Entry(width=20)
e.grid(row=0,column=4)
b1 = Button(text="1",height=4,width=8,command=lambda:sum.num_press(1)).grid(row=0,column=0)
b2 = Button(text="2",height=4,width=8,command=lambda:sum.num_press(2)).grid(row=0,column=1)
# it goes up to b9
equals = Button(text="=",height=4,width=8,command=lambda:sum.calc_total).grid(row=3,column=2)
add = Button(text="+",height=4,width=8,command=lambda: sum.operation("add")).grid(row=3,column=1)
minus = Button(text="-",height=4,width=8,command=lambda: sum.operation("minus")).grid(row=3,column=0)
clear = Button(text="AC",height=4,width=8,command=lambda:sum.clear).grid(row=3,column=3)
root.mainloop()
You can do it as follows. I have shown for only one operator and one number. You can add more to it.
#This is for python 3
import tkinter as tk #Import Tkinter for python2
from tkinter import *
root=tk.Tk()
X=StringVar()
def calculations():
v=e1.get()
val=eval(v)
l=Label(root, text=str(val)).grid()
e1=Entry(root,textvariable=X)
e1.grid()
b1=Button(root, text="1", command=lambda:e1.insert(END,str(1))).grid()
bp=Button(root, text="+", command=lambda:e1.insert(END,str("+"))).grid()
b=Button(root, text="=", command=lambda: calculations()).grid()
root.mainloop()
Hope this helps