good day! here's my code:
import tkinter as tk
namemass =["dev", "Dev1"]
self.entry_name = ttk.Entry(self)
self.entry_name.place(x=200, y=50)
btn_cancel = ttk.Button(self, text="cancel", command=self.destroy)
btn_cancel.place(x=300, y=800)
btn_ok = ttk.Button(self, text="ok")
btn_ok.place(x=320, y=170)
so, i have 2 buttons and enter box. I want the program to get the text from the enter box and if namemass list have that inside, then exit. in console program i would code it like that:
name = input()
namemass = ["dev", "Dev1"]
if name in namemass:
import sys
sys.exit()
else:
..........
how to do it using tkinter? thank you in advance!
To fetch the current entry text, use the get method:
current_text = Entry.get()
in your example you can just:
from tkinter import *
import sys
def destroy():
name = entry_name.get()
if name in namemass:
sys.exit()
root = Tk()
namemass = ["dev", "Dev1"]
entry_name = Entry(root)
entry_name.pack()
btn_cancel = Button(root, text="cancel", command=destroy)
btn_cancel.pack()
btn_ok = Button(root, text="ok")
btn_ok.pack()
root.mainloop()
Much easier for Python 3.8, using Walrus. Just add the function for _ok. And add command in btn_ok.
from tkinter import *
import sys
namemass = ["dev", "Dev1"]
def destroy():
#sys.exit()
root.destroy()
def _ok():
if(name_in_list := entry_name.get()) in namemass:
sys.exit()
root = Tk()
entry_name = Entry(root)
entry_name.pack()
btn_cancel = Button(root, text="cancel", command=destroy)
btn_cancel.pack()
btn_ok = Button(root, text="ok", command=_ok)
btn_ok.pack()
root.mainloop()
Related
Need help solving this problem, I'm a beginner going crazy over this. Each time I press "pingButton1" I want the "pingResult1" to refresh the information insteed of adding new every time I press it. It's a simple "check if ping is good" program.
Any suggestions?
stacking
I've tried using google but nothing is working for me.
from tkinter import *
import os
import subprocess
from time import sleep
menu = Tk()
menu.title("Panel")
menu.geometry("250x380+700+500")
menu.resizable(0, 0)
menu.configure(background="#0d335d")
def close():
screen.destroy()
def pingWindow1():
global ip1
global pingButton1
global screen
screen = Toplevel(menu)
screen.title("Ping Windows")
screen.geometry("300x250+650+300")
screen.configure(background="#0d335d")
blank = Label(screen, bg="#0d335d", text="")
blank.pack()
ip1 = Entry(screen, width=20, bg="white")
ip1.pack()
blank1 = Label(screen, bg="#0d335d", text="")
blank1.pack()
pingButton1 = Button(screen, text="Ping away..", width="20", bg="#e5e5e5", height="2", borderwidth=2, relief="ridge", command=pingResult1)
pingButton1.pack()
close_ping = Button(screen, text="Close", width="20", bg="#e5e5e5", height="2", borderwidth=2, relief="ridge", command=close)
close_ping.pack()
blank2 = Label(screen, text="", bg="#0d335d")
blank2.pack()
screen.bind('<Escape>', lambda _: close())
def pingResult1():
global pingIP1
pingIP1 = ip1.get()
try:
overall_mgm()
except:
return False
try:
overall_mgm_RO()
except:
return False
done = Label(screen, text="Completed").pack()
def overall_mgm():
response = os.system("ping -c 1 sekiiws00"+pingIP1)
if response is not 0:
fail = Label(screen, bg="black", fg="red", text="KI FAILED").pack()
else:
success = Label(screen, bg="black", fg="green", text="KI SUCCESS").pack()
def overall_mgm_RO():
response = os.system("ping -c 1 seroiws00"+pingIP1)
if response is not 0:
fail = Label(screen, bg="black", fg="red", text="RO FAILED").pack()
else:
success = Label(screen, bg="black", fg="green", text="RO SUCCESS").pack()
# Widget
option = Button(menu, text="Ping IP", width="20", bg="#e5e5e5",height="2", borderwidth=2, relief="ridge", command=pingWindow1)
# Out
option.pack()
menu.mainloop()
I'm guessing I need something like this
if pingButton1 clicked more than once
refresh current Labels( fail & success)
def pingResult1():
global pingIP1
pingIP1 = ip1.get()
try:
overall_mgm()
except:
return False
try:
overall_mgm_RO()
except:
return False
done = Label(screen, text="Completed").pack()
with this demo you can change button's text (for example) when pressed.
import tkinter
from functools import partial
# partial is good for passing `function` and `its args`
def button_command(button):
# for example
button.config(text="another value")
# creating new button
# root is whatever you want
button = tkinter.Button(root, text="something")
# add command to button and passing `self`
button.config(command=partial(button_command, button))
button.pack()
adapt this example to your code and you are good to go.
what I want to do, is to open from the root window a toplevel window in which I have series of entry widgets, modify the entries and close the window. I found a code in one of the posts and modified it to fit my need. The code works only the first time I open the toplevel window, but after that it opens the toplevel window without the entry fields! I don't understand what is happening!! Can anyone help please? I am quite new to python. Here is the code:
from tkinter import *
root = Tk()
entry_list = []
def openwindow():
window = Toplevel()
window.title("Data")
entry_list.clear()
for i in range(10):
entry_list.append(Entry(window))
entry_list[i].grid()
def update_entry_fields():
for i in entry_list:
i.delete(END)
i.insert(0, "")
print(float(entry_list[0].get()))
def closewindow():
window.withdraw()
savebtn = Button(window, text="Save & print", command = update_entry_fields)
closebtn = Button(window, text="Close", command=closewindow)
savebtn.grid()
closebtn.grid()
def printout():
print(float(entry_list[0].get()))
printbtn = Button(root, text="Test print", command = printout)
printbtn.grid()
openbutton = Button(root, text="open data sheet", command=openwindow)
openbutton.grid()
root.mainloop()
Here is the solution that at least i was looking for.
from tkinter import *
root = Tk()
entry_list = []
p = [5, 6, 7, 8, 9]
def openwindow():
window = Toplevel()
window.title("Data")
entry_list.clear()
for i in range(5):
v = DoubleVar()
entry_list.append(Entry(window, textvariable=v))
entry_list[i].grid()
v.set(p[i]) # set default entry values
def update_entry_fields():
for i in range(5):
p[i]=entry_list[i].get() # overwrite the entry
# test print from inside
print(p[i])
window.withdraw()
savebtn = Button(window, text="Save & close", command = update_entry_fields)
savebtn.grid()
window.mainloop()
# Test print from outside of function
def printout():
print(p[0])
printbtn = Button(root, text="Test print", command = printout)
printbtn.grid()
openbutton = Button(root, text="open data sheet", command=openwindow)
openbutton.grid()
#
root.mainloop()
I can't generate the number because I get the error NameError: name 'z' is not defined.
import tkinter as tk
from random import randint
def randomize():
z.set ( randint(x.get(),y.get()))
root = tk.Tk()
x = tk.IntVar()
y = tk.IntVar()
text= tk.Label(root, text = "press the button for random number")
enterX = tk.Entry(root)
enterY = tk.Entry(root)
button = tk.Button(root, text = "Press here", command=randomize)
result = tk.Label(root,text="Number is:")
number = tk.Label(root, textvariable=z)
text.pack()
enterX.pack()
enterY.pack()
button.pack()
result.pack()
number.pack()
root.mainloop()
I need help to resolve the error
You have 2 problems here.
One. You are missing z = tk.Intvar() in the global namespace.
Two. You need to assign each entry field one of the IntVar()'s.
Keep in mind that you are not validating the entry fields so if someone types anything other than a whole number you will run into an error.
Take a look at this code.
import tkinter as tk
from random import randint
def randomize():
z.set(randint(x.get(),y.get()))
print(z.get()) # added print statement to verify results.
root = tk.Tk()
x = tk.IntVar()
y = tk.IntVar()
z = tk.IntVar() # added IntVar()
text= tk.Label(root, text = "press the button for random number")
enterX = tk.Entry(root, textvariable=x) # added textvariable
enterY = tk.Entry(root, textvariable=y) # added textvariable
button = tk.Button(root, text = "Press here", command=randomize)
result = tk.Label(root,text="Number is:")
number = tk.Label(root, textvariable=z)
text.pack()
enterX.pack()
enterY.pack()
button.pack()
result.pack()
number.pack()
root.mainloop()
I want to select one of installed printer on my computer and print through it but my combobox doesn't display the printers on my machine but rather print to my terminal in my IDE .
Have been trying this for days with arriving at the solution to do this.Have installed the win32print module to after reading about it.This my code below:
from tkinter import *
from tkinter import ttk
import win32print
def installed_printer():
printers = win32print.EnumPrinters(2)
for p in printers:
return(p)
def locprinter():
pt = Toplevel()
pt.geometry("250x250")
pt.title("choose printer")
LABEL = Label(pt, text="select Printer").pack()
PRCOMBO = ttk.Combobox(pt, width=35,
textvariable=installed_printer).pack()
BUTTON = ttk.Button(pt, text="refresh",
command=installed_printer).pack()
root = Tk()
root.title("printer selection in tkinter")
root.geometry("400x400")
menubar = Menu(root)
root.config(menu=menubar)
file_menu = Menu(menubar)
menubar.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="printer", command=locprinter)
LAB = Label(root, text="Comment")
T2 = Text(root, width=40, height=10)
def INFO():
print(T2.get("1.0", END))
Print_Button = Button(root, text ="Print", command =
INFO).place(x=180,y=250)
LAB.pack()
T2.pack()
root.mainloop()
How can i achieve this as i want to print the content in my Text box with tkinter framework.
Is this what you wanted to create?
from tkinter import *
from tkinter import ttk
import win32api
import win32print
import tempfile
def installed_printer():
printers = win32print.EnumPrinters(2)
for p in printers:
return(p)
printerdef = ''
def locprinter():
pt = Toplevel()
pt.geometry("250x250")
pt.title("choose printer")
var1 = StringVar()
LABEL = Label(pt, text="select Printer").pack()
PRCOMBO = ttk.Combobox(pt, width=35,textvariable=var1)
print_list = []
printers = list(win32print.EnumPrinters(2))
for i in printers:
print_list.append(i[2])
print(print_list)
# Put printers in combobox
PRCOMBO['values'] = print_list
PRCOMBO.pack()
def select():
global printerdef
printerdef = PRCOMBO.get()
pt.destroy()
BUTTON = ttk.Button(pt, text="Done",command=select).pack()
root = Tk()
root.title("printer selection in tkinter")
root.geometry("400x400")
menubar = Menu(root)
root.config(menu=menubar)
file_menu = Menu(menubar)
menubar.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="printer", command=locprinter)
LAB = Label(root, text="Comment")
T2 = Text(root, width=40, height=10, wrap=WORD)
def INFO():
printText = T2.get("1.0", END)
print(printText)
print(printerdef)
filename = tempfile.mktemp(".txt")
open(filename, "w").write(printText)
# Bellow is call to print text from T2 textbox
win32api.ShellExecute(
0,
"printto",
filename,
'"%s"' % win32print.GetDefaultPrinter(),
".",
0
)
Print_Button = Button(root, text ="Print", command=INFO).place(x=180,y=250)
LAB.pack()
T2.pack()
root.mainloop()
I'm building a python GUI and there I got 2 text boxes.
I want to create a submit button that will take the data from those 2 text boxes and send them to start(save_place, website_url) function.
This is what I got so far:
from Tkinter import *
def start(save_place, website_url):
#something
app = Tk()
top_app = Frame(app)
top_app.pack()
save_location = Entry(top_app, width=20)
url = Entry(top_app, width=20)
save_location.grid(sticky=W, row=0)
url.grid(sticky=W, row=1)
save_place = save_location.get("1.0", END)
website_url = url.get("1.0", END)
button_start = Button(top_app, text="Start", fg="green", command=start(save_place,website_url))
button_start.grid(sticky=W, row=2, pady=20)
app.mainloop()
I also tried this:
from Tkinter import *
def start():
save_place = save_loc.get()
website_url = urls.get()
print (save_place + " " + website_url)
app = Tk()
top_app = Frame(app)
top_app.pack()
save_loc = StringVar()
save_location = Entry(top_app, textvariable=save_loc, width=85)
urls = StringVar()
url = Entry(top_app, textvariable=urls, width=85)
button_start = Button(top_app, text="Start", fg="green", command=start)
button_start.grid(sticky=W, row=2, pady=20)
app.mainloop()
And it didn't work.
How can I make this script send the inputs in the text boxes to the function?
Thanks to all the helpers :)
As mentioned in the previous response "about how to call a function", you just put command = start and put save_place = save_location.get()
in start function, however you can use save_location = Entry(top_app, width=20), so the total prg:
from Tkinter import *
def start():
#something
save_place = save_location.get()
website_url = url.get()
print save_place,website_url
app = Tk()
top_app = Frame(app)
top_app.pack()
save_location = Entry(top_app, width=20)
url = Entry(top_app, width=20)
save_location.grid(sticky=W, row=0)
url.grid(sticky=W, row=1)
button_start = Button(top_app, text="Start", fg="green", command=start)
button_start.grid(sticky=W, row=2, pady=20)
app.mainloop()
command=start(save_place,website_url) doesn't do what you think its doing. It's assigning the result of the function call to the command. (Which is probably None). Bind your Entry boxes to StringVar like:
location = StringVar()
Entry(top_app, textvariable=location, width=20)
Then you assign the function call to the command parameter using command = start. Inside the function you can access the value in the Entry using location.get(). To set the value use the corresponding method location.set(value)