The idea of the code is to create N amount of buttons that copy text to the clipboard when pressed, overwriting and saving the text from the last pressed button.
from tkinter import *
import tkinter
r = Tk()
age = '''
O.o
giga
'''
gage = 'vrum'
r.title("getherefast")
def gtc(dtxt):
r.withdraw()
r.clipboard_clear()
r.clipboard_append(dtxt)
r.update()
tkinter.Button(text='age', command=gtc(age)).grid(column=1, row=0)
tkinter.Button(text='gage', command=gtc(gage)).grid(column=2, row=0)
r.mainloop()
With this code I expected to get 2 buttons 'age' and 'gage' and when I press them to get respectively the value saved in the var.
The problem is that the tkinter UI does not load and the Idle window is just standing open.
The result is that I get 'vrum' copied to the clipboard (If age button is the only 1 present I get the correct value but still no GUI from tkinter).
As additional information I'm writing and testing the code in IDLE, Python 3.10.
The problem is that the tkinter UI does not load
Yes it does, but you told it to withdraw(), so you don't see it.
To do this you need a partial or lambda function, you can't use a normal function call in a command argument. Try this:
import tkinter
r = tkinter.Tk()
age = '''
O.o
giga
'''
gage = 'vrum'
r.title("getherefast")
def gtc(dtxt):
r.clipboard_clear()
r.clipboard_append(dtxt)
tkinter.Button(text='age', command=lambda: gtc(age)).grid(column=1, row=0)
tkinter.Button(text='gage', command=lambda: gtc(gage)).grid(column=2, row=0)
r.mainloop()
Related
This question already has answers here:
Why is my Button's command executed immediately when I create the Button, and not when I click it? [duplicate]
(5 answers)
Closed last year.
I wanted to make button in tkinter, but when I started program, the command always calls when code just starts.
Here is example code:
import tkinter as tk
from tkinter import messagebox
window = tk.Tk()
window.title("Why this don't works???")
window.wm_geometry("100x100")
def message():
messagebox.showinfo("Hi there")
button = tk.Button(text="Hello", command=message())
button.grid(column=0, row=0)
while True:
window.update()
And then, button didn't worked. (When you press it, it don't works.)
I don't know what I'm doing wrong, so I need help.
The command should be a pointer to a function
In the code you wrote, the command gets the return value from the function.
command=message()
The correct way is
command = message
The problem is you are requesting a return value from the fucnction. Try using this.
from tkinter import *
# import messagebox from tkinter module
import tkinter.messagebox
# create a tkinter root window
root = tkinter.Tk()
# root window title and dimension
root.title("When you press a button the message will pop up")
root.geometry('75x50')
# Create a messagebox showinfo
def onClick():
tkinter.messagebox.showinfo("Hello World!.", "Hi I'm your message")
# Create a Button
button = Button(root, text="Click Me", command=onClick, height=5, width=10)
# Set the position of button on the top of window.
button.pack(side='top')
root.mainloop()
You have 2 errors:
first:
It must be command=message
second:
You must give a message argument too, you entered a title only.
Or, what you can do is.
Add another variable.
command = message()
Before this line,
button = tk.Button(text="Hello", command=message())
And chande this line to,
button = tk.Button(text="Hello", command=command)
I am trying to get a Tkinter popup to display when a button is clicked.My issue is that every thing runs just fine except the popup will not produce. I have tried multiple ways to create the popup using tkMessagebox and Toplevel() but still not luck. The program runs but when the button is click nothing happens. I have referenced similar post but still can not find the issue in my code. Any thoughts?
from tkinter import *
def new():
root2 = Tk()
root2.geometry('250x250')
l = Label(root2,text="Please Scan Tag").pack()
root2.mainloop()
# setting main frame
root = Tk()
root.geometry('800x650')
root.title("Pass")
root.configure(background= "white")
label_0 = Label(root, text="Pass",width=10,font=("bold", 50),fg= "green",bg="white")
label_0.place(x=186,y=76)
Button(root,command="new", text='new',font=
("bold",15),width=15,height=4,bg='blue',fg='white').place(x=155,y=300)
root.mainloop()
The command option requires a reference to a callable function, not a string.
Button(root,command=new, ...)
There have already been several topics on Python/Tkinter, but I did not find an answer in them for the issue described below.
The two Python scripts below are reduced to the bare essentials to keep it simple. The first one is a simple Tkinter window with a button, and the script needs to wait till the button is clicked:
from tkinter import *
windowItem1 = Tk()
windowItem1.title("Item1")
WaitState = IntVar()
def submit():
WaitState.set(1)
print("submitted")
button = Button(windowItem1, text="Submit", command=submit)
button.grid(column=0, row=1)
print("waiting...")
button.wait_variable(WaitState)
print("done waiting.")
windowItem1.mainloop()
This works fine, and we see the printout “done waiting” when the button is clicked.
The second script adds one level: we first have a menu window, and when clicking the select button of the first presented item, we have a new window opening with the same as above. However, when clicking the submit button, I don’t get the “Done waiting”. I’m stuck on the wait_variable.
from tkinter import *
windowMenu = Tk()
windowMenu.title("Menu")
def SelectItem1():
windowItem1 = Tk()
windowItem1.title("Item1")
WaitState = IntVar()
def submit():
WaitState.set(1)
print("submitted")
button = Button(windowItem1, text="Submit", command=submit)
button.grid(column=0, row=1)
print("waiting...")
button.wait_variable(WaitState)
print("done waiting")
lblItem1 = Label(windowMenu, text="Item 1 : ")
lblItem1.grid(column=0, row=0)
btnItem1 = Button(windowMenu, text="Select", command=SelectItem1)
btnItem1.grid(column=1, row=0)
windowMenu.mainloop()
Can you explain it?
Inside your SelectItem1 function, you do windowItem1 = Tk(). You shouldn't use Tk() to initialize multiple windows in your application, the way to think about Tk() is that it creates a specialized tkinter.Toplevel window that is considered to be the main window of your entire application. Creating multiple windows using Tk() means multiple main windows, and each one would need its own mainloop() invokation, which is... yikes.
Try this instead:
windowItem1 = Toplevel()
So, I have rather complicated program, and I ran into an issue with it that I can't seem to solve.
Here's the problematic part of my program:
import tkinter as tk
window = tk.Tk()
variable = "enter"
vars()[variable] = tk.Entry()
vars()[variable].insert(0, "hello")
vars()[variable].pack()
def hi():
text = vars()[variable].get()
button = tk.Button(text = "Click", command = hi)
button.pack()
I need to get the content of the entry called "enter" with the press of a button. Because of how my program works, this name, "enter" must be stored in a variable, that I called "variable" here.
What happens, is that when I press the button, I get a KeyError.
What's even weirder is that when I do the following, the program actualy works:
import tkinter as tk
window = tk.Tk()
variable = "enter"
vars()[variable] = tk.Entry()
vars()[variable].insert(0, "hello")
vars()[variable].pack()
text = vars()[variable].get()
button = tk.Button(text = "Click")
button.pack()
Here getting the content of "enter" isn't done with a button, but it's done automatically as the program runs. This is not what I want, but for some reason it works.
What can I do to make the 1st code work properly?
When you execute vars locally within hi function, a new dict object is created, that is different than the dict object created globally.
You can save the reference to the variable and use the variable within your hi function.
import tkinter as tk
window = tk.Tk()
variable = "enter"
vars()[variable] = tk.Entry()
vars()[variable].insert(0, "hello")
vars()[variable].pack()
d = vars()
def hi():
text = d[variable].get()
button = tk.Button(text="Click", command=hi)
button.pack()
window.mainloop()
I need to get the content of the entry called "enter" with the press of a button. Because of how my program works, this name, "enter" must be stored in a variable,
A better solution than using vars()[variable] is to store your widgets in a dictionary. The use of vars() provides very little value at the expense of making the code harder to understand.
import tkinter as tk
window = tk.Tk()
variable = "enter"
widgets = {}
widgets[variable] = tk.Entry()
widgets[variable].insert(0, "hello")
widgets[variable].pack()
def hi():
text = widgets[variable].get()
print(text)
button = tk.Button(text = "Click", command = hi)
button.pack()
I am trying to click a tkinter button to open up a new tkinter window to execute a script within it all the way up to the end with a scroll bar if necessary. However, I have only succeeded this far in getting it to run in multitude of ways in a linux window and not within a tkinter window. Can someone help me with redirecting the output of this script into the toplevel window?
self.button_run = Button(self, text="RUN", width=16, command=self.callpy)
self.button_run.grid(row=25, column=0, columnspan=2, sticky=(W + E + N + S))
def run_robbot(self):
new = Toplevel(self)
new.geometry('500x200')
label = Message(new, textvariable=self.callpy, relief=RAISED)
label.pack()
def callpy(self):
pyprog = 'check_asim.robot'
call(['robot', pyprog])
In the snippet above, if I pass callpy to command in Button it runs the robot script in a linux window. If I replace it to call run_robbot which is what I want and expect, it just pops up a new window with a Message Box without running the same script passed to textvariable. I have tried Enter in place of Message Box as well.
I want callpy to be executed in Toplevel tkinter window at the click of the button. How do I do it? Any tkinter operator is fine as long as it confines to the tkinter window.
If you want to capture the output of the command, you should use subprocess.run(cmd,capture_output=True) instead. Below is an sample code:
import subprocess
from tkinter import *
class App(Tk):
def __init__(self):
Tk.__init__(self)
Button(self, text='Run', command=self.run_robot).pack()
def run_robot(self):
win = Toplevel(self)
win.wm_attributes('-topmost', True)
output = Text(win, width=80, height=20)
output.pack()
output.insert(END, 'Running ....')
output.update()
result = self.callpy()
output.delete(1.0, END)
output.insert(END, result)
def callpy(self):
pyprog = 'check_asim.robot'
return subprocess.run(['robot', pyprog], capture_output=True).stdout
App().mainloop()