I've been working with Tkinter and I'm having a problem with spinbox. I have spinbox set to: from_=1, to=5. No mater what I do spinbox outputs a 5 as it's variable. I've read lot's of post here on other's answer for related questions and can't seem to find an answer.
Clicking the mouse and selecting a value in the spinbox does nothing.
Here is the code :
sp1=Spinbox(root, bd=3, state='readonly', from_=1, to=5, font="bold", wrap="true")
sp1.grid(row=3, column=2, padx=20)
sp1.delete(0, END)
sp1.bind("<Button-1>")
i=sp1.get()
i is always equal to 5.
You can assign function to Spinbox using command= and this function will be executed everytime you change value in Spinbox. And then you can get value from Spinbox. Now you get value only at start.
import tkinter as tk
# --- functions ---
def callback():
print("value:", w.get())
# --- main ---
root = tk.Tk()
w = tk.Spinbox(root, state='readonly', from_=1, to=5, command=callback)
w.pack()
root.mainloop()
You can pass a callback function to the command argument when you initialize the Spinbox:
# python 3
from tkinter import *
# python 2
#from Tkinter import *
root = Tk()
def on_spinbox_change():
print(sp1.get())
sp1 = Spinbox(root, bd=3, state='readonly', from_=1, to=5, font="bold", wrap="true", command=on_spinbox_change)
sp1.grid(row=3, column=2, padx=20)
root.mainloop()
Related
I'm able to select both the combo box successfully but to print the second dropdown box value, I got lost. Could somebody explain how to print the Table value from the 2nd drop down box.
Note: The two drop downs are dependabale.
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title("ETL")
Environment = ["UAT","ITEST","PROD"]
Tables = [["USER_UAT","IP_UAT"],
["USER_ITEST","IP_ITEST"],
["USER_PROD","IP_PROD"]]
envi= ttk.Combobox(root,width =37, value=(Environment))
envi.grid(row=3,column=1,columnspan=2, padx=10, pady=2, sticky='w')
def callback(eventObject):
abc = eventObject.widget.get()
en = envi.get()
index=Environment.index(en)
tab.config(values=Tables[index])
tab=ttk.Combobox(root, width=37)
tab.grid(row=4,column=1,columnspan=2, padx=10, pady=2, sticky='w')
tab.bind('<Button-1>', callback)
root.mainloop()
The most straightforward way is to add a separate event binding for each combobox. I changed the bindings from <Button-1> to <<ComboBoxSelect>> as this prevents the events from being fired every time a combobox is clicked - instead, events will only fire when a selection is actually made.
I also added some code to set the combobox default values as well as to update the value of the second combobobox whenever a selection is made in the first combobox.
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title('ETL')
environment = ['UAT', 'ITEST', 'PROD']
tables = [
['USER_UAT', 'IP_UAT'],
['USER_ITEST', 'IP_ITEST'],
['USER_PROD', 'IP_PROD'],
]
def populate_table_combobox(event):
index = environment.index(env_combo.get())
table_combo.config(values=tables[index])
table_combo.current(0) # update the 'table' selection when 'env' changes
def get_table_combo_value(event):
print(table_combo.get()) # YOUR CODE HERE!
env_combo = ttk.Combobox(root, width=37, value=environment)
env_combo.current(0) # set default value
env_combo.grid(row=3, column=1, columnspan=2, padx=10, pady=2, sticky='w')
table_combo = ttk.Combobox(root, width=37, values=tables[0])
table_combo.current(0) # set default value
table_combo.grid(row=4, column=1, columnspan=2, padx=10, pady=2, sticky='w')
env_combo.bind('<<ComboBoxSelected>>', populate_table_combobox)
table_combo.bind('<<ComboBoxSelected>>', get_table_combo_value)
root.mainloop()
I'm trying to build a very simple program in Python and Tkinter that allows the user to input people's names by keyboard and then a button is commanded to select a person from the list at random and show it in a tk.Label object.
My problem is once I run the root.mainloop(), I can add names to the list but the list does not update with the new names.
This is the main code for the Tkinter to initialize
import tkinter as tk
from tkinter import filedialog, Text
import random
root = tk.Tk()
root.title('Millor persona del moment')
root.geometry("500x200")
root.configure(bg='black')
peopleList = []
tk.Label(root, text="Insertar participante: ",fg="#ff007f", bg='black').grid(row=0)
e1 = tk.Entry(root)
e1.grid(row=0, column=1)
addButton = tk.Button(root, text='AƱadir', padx=10, pady=5, fg="#ff007f", bg='black', command=addPerson)
addButton.grid(row=0, column=2)
while peopleList:
turnButton = tk.Button(root, text='Saca Tema', padx=10, pady=5, fg="#ff007f", bg='black', command=wordTurn(peopleList))
turnButton.grid(row=1, column=0)
nom = tk.StringVar()
nom.set('Comencem')
personSpeaking = tk.Label(root, textvariable=nom,fg="#ff007f", bg='black')
personSpeaking.grid(row=1, column=1)
root.mainloop()
And these are the functions I use
def addPerson():
peopleList.append(e1.get())
e1.delete(0,'end')
def wordTurn(peopleList):
person = random.choice(peopleList)
peopleList.remove(person)
nom.set(person)
command=wordTurn(peopleList)) calls the return value of wordTurn when the button is pressed, which is None and should raise an error. Use command=lambda peopleList=peopleList: wordTurn(peopleList)) instead.
I been searching for methods to copy text to clipboard or copy the results from Tkinter gui but idk if there is a command or something
here is my code for now here the result comes in a messagebox can i copy it to clipboard
import tkinter.messagebox
import string
import random
def qs_msgbbox(): # qs_msgbbox
tkinter.messagebox.showinfo("Info", "For customer support or tip or rating contact:"
"dghaily725#gmail.com\npress the button for generated pass\nmsg will appear then copy\nthe generated password")
def gen_pass(k=9): # gen_pass
char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*"
password = ''
for i in range(9):
password += random.choice(char)
tkinter.messagebox.showinfo("Password", password)
root = Tk()
root.title("Password Generator")
lbl1 = Label(root, text="Generate Password", bd=2, relief=SUNKEN, height=5, width=50, bg='black', fg='white')
lbl1.configure(font=(70))
lbl1.grid(row=0, column=2)
lbl2 = Label(root, text='For more information press the Question mark', bd=2, relief=SUNKEN, fg='red')
lbl2.configure(font=(70))
lbl2.grid(row=0, column=0, pady=10)
btn1 = Button(root, text='Press to Generate', height=5, width=50, bg='grey', command=gen_pass)
btn1.configure(font=(70))
btn1.grid(row=1, column=2, padx=460, pady=50)
btn2photo = PhotoImage(file='question.png')
btn2 = Button(root, image=btn2photo, width=30, height=30, command= qs_msgbbox)
btn2.grid(row=0, column=1)
root.mainloop()
and also just a quick small question is it better to use classes or this form
Tkinter does have a function for that, simply just
from tkinter import Tk
root = Tk()
root.clipboard_clear()
root.clipboard_append("Something to the clipboard")
root.update() # the text will stay there after the window is closed
Hope I could help
Greets
The above answer is perfectly fine. Infact its the method to do it. I read the comments, He had mentioned that it could only take in string. That is completely false. It can also take in functions. For example..
import tkinter as tk
root = tk.Tk()
#creating a entry Widget.(Labels are fine as well)
entry = tk.Entry(root)
entry.pack()
#NOW if you want to copy the whole string inside the above entry box after you
typed in #
def copy ():#assign this function to any button or any actions
root.clipboard_clear()
root.clipboard_append(entry.get()) #get anything from the entry widget.
root.mainloop()
Hoping this was helpful
In my Gui Application I have buttons for each widget.If the user click on button named as label a label widget will be formed on window.I am asking the user to set label properties (bg color and fg color) through entry widget and i need to update that existing label using those properties.
Is there any way to do this?
from tkinter import *
def try1():
w=Tk()
l=Label(w,text="Hi")
l.pack()
win=Tk()
b=Button(win,text="Label",command=try1)
b.pack()
ety_bgcolor=Entry(win,font=("",13,""), borderwidth=2, relief="groove")
ety_bgcolor.pack()
ety_fgcolor=Entry(win,font=("",13,""), borderwidth=2, relief="groove")
ety_fgcolor.pack()
Use configure method to change Label properties.
Example to change bg color and fg color:
label.configure(background='yellow')
label.configure(foreground='red')
Misunderstood the question edit:
from tkinter import *
def try1():
w=Tk()
l=Label(w,text="Hi")
l.config(bg=bgcolor.get())
l.config(fg=fgcolor.get())
l.pack()
win=Tk()
b=Button(win,text="Label",command=try1)
b.pack()
bgcolor = StringVar()
ety_bgcolor=Entry(win,font=("",13,""), borderwidth=2, relief="groove",textvariable=bgcolor)
ety_bgcolor.pack()
fgcolor = StringVar()
ety_fgcolor=Entry(win,font=("",13,""), borderwidth=2, relief="groove",textvariable=fgcolor)
ety_fgcolor.pack()
win.mainloop()
If i understand you correctly you want the main window to get a new label when the user clicks the button?
If so you need to pass the main window to the function, either using the global name or passing it as a variable in the function using a lambda function.
Using global:
from tkinter import *
def try1():
w=win # referencing the main window globally
l=Label(w,text="Hi")
l.pack()
win=Tk()
b=Button(win,text="Label",command=try1)
b.pack()
ety_bgcolor=Entry(win,font=("",13,""), borderwidth=2, relief="groove")
ety_bgcolor.pack()
ety_fgcolor=Entry(win,font=("",13,""), borderwidth=2, relief="groove")
ety_fgcolor.pack()
win.mainloop()
With the lambda method:
from tkinter import *
def try1(w): # getting the main window passed
l=Label(w,text="Hi")
l.pack()
win=Tk()
b=Button(win,text="Label",command = lambda: try1(win)) # passing the main window.
b.pack()
ety_bgcolor=Entry(win,font=("",13,""), borderwidth=2, relief="groove")
ety_bgcolor.pack()
ety_fgcolor=Entry(win,font=("",13,""), borderwidth=2, relief="groove")
ety_fgcolor.pack()
win.mainloop()
if you want the colors to be set, you have to add string variables to the entry field and reference those when setting the labels config settings.
from tkinter import *
def try1(w):
l=Label(w,text="Hi")
l.config(bg=bgcolor.get())
l.config(fg=fgcolor.get())
l.pack()
win=Tk()
b=Button(win,text="Label",command = lambda: try1(win))
b.pack()
bgcolor = StringVar()
ety_bgcolor=Entry(win,font=("",13,""), borderwidth=2, relief="groove",textvariable=bgcolor)
ety_bgcolor.pack()
fgcolor = StringVar()
ety_fgcolor=Entry(win,font=("",13,""), borderwidth=2, relief="groove",textvariable=fgcolor)
ety_fgcolor.pack()
win.mainloop()
You simply have to call the get methods on the entry widgets to get their value before creating the label.
def try1():
...
bg = ty_bgcolor.get()
fg = ety_fgcolor
l=Label(w,text="Hi", background=bg, foreground=fg)
...
I have a GUI using Tkinter, it has a main screen and then when you press a button a popup window appears, where you select a checkbutton and then a email will get sent to you.
Not matter what I do, I cannot read the value of the checkbutton as 1 or True it always = 0 or False.
This is my code:
import tkinter as tk
from tkinter import *
import time
root = tk.Tk()
root.title('Status')
CheckVar1 = IntVar()
def email():
class PopUp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
popup = tk.Toplevel(self, background='gray20')
popup.wm_title("EMAIL")
self.withdraw()
popup.tkraise(self)
topframe = Frame(popup, background='gray20')
topframe.grid(column=0, row=0)
bottomframe = Frame(popup, background='gray20')
bottomframe.grid(column=0, row=1)
self.c1 = tk.Checkbutton(topframe, text="Current", variable=CheckVar1, onvalue=1, offvalue=0, height=2, width=15, background='gray20', foreground='snow', selectcolor='gray35', activebackground='gray23', activeforeground='snow')
self.c1.pack(side="left", fill="x", anchor=NW)
label = tk.Label(bottomframe, text="Please Enter Email Address", background='gray20', foreground='snow')
label.pack(side="left", anchor=SW, fill="x", pady=10, padx=10)
self.entry = tk.Entry(bottomframe, bd=5, width=35, background='gray35', foreground='snow')
self.entry.pack(side="left", anchor=S, fill="x", pady=10, padx=10)
self.button = tk.Button(bottomframe, text="OK", command=self.on_button, background='gray20', foreground='snow')
self.button.pack(side="left", anchor=SE, padx=10, pady=10, fill="x")
def on_button(self):
address = self.entry.get()
print(address)
state = CheckVar1.get()
print (state)
time.sleep(2)
self.destroy()
app = PopUp()
app.update()
tk.Button(root,
text="EMAIL",
command=email,
background='gray15',
foreground='snow').pack(side=tk.BOTTOM, fill="both", anchor=N)
screen = tk.Canvas(root, width=400, height=475, background='gray15')
screen.pack(side = tk.BOTTOM, fill="both", expand=True)
def latest():
#Other code
root.after(300000, latest)
root.mainloop()
The popup works perfectly, and the email will print when entered but the value of checkbox is always 0.
I have tried:
CheckVar1 = tk.IntVar() - No success
self.CheckVar1 & self.CheckVar1.get() - No success
Removing self.withdraw() - No success
I only have one root.mainloop() in the script, I am using app.update() for the popup window because without this it will not open.
I have checked these existing questions for solution and none have helped:
Self.withdraw - Can't make tkinter checkbutton work normally when running as script
Self.CheckVar1 - TKInter checkbox variable is always 0
Only one instance of mainloop() - Python tkinter checkbutton value always equal to 0
I have also checked very similar questions but I wasn't going to post them all.
Any help is appreciated.
The problem is that you have two root windows. Each root window gets its own internal tcl interpreter, and the widgets and tkinter variables in one are completely invisible to the other. You're creating the IntVar in the first root window, and then trying to associate it with a checkbutton in a second root window. This cannot work. You should always only have a single instance of Tk in a tkinter program.
because of variable scope
try to put CheckVar1 = IntVar() inside the class
use it with self like this
self.CheckVar1 = tk.IntVar() # object of int
self.CheckVar1.set(1) # set value
variable=self.CheckVar1 # passing to the checkbutton as parameter
state = self.CheckVar1.get() # getting value