from tkinter import *
from tkinter import messagebox, simpledialog
from tkinter.messagebox import askokcancel, showinfo, WARNING
app = []
def main():
USER_INP = simpledialog.askstring(title="App Name",
prompt="Insert the name of the app:")
print(USER_INP)
answer = askokcancel(
title='DELETION',
message='Are you sure?',
icon=WARNING)
if answer:
print(answer)
messagebox.showinfo("INFO", "User pressed yes")
app.append(USER_INP)
else:
messagebox.showinfo("INFO", "User pressed cancel")
root = Tk()
myButton = Button(root, text='input', command=main)
myButton.pack()
root.mainloop()
What I want to happen here is if the user presses the input button, then the Insert the app name window pops up. If he presses cancel I want it to just stop there and do nothing. To be more exact I dont want it to go into the answer = askokcancel part.
if USER_INP is None:
return
I just used this
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 still working on the translator app, with the help of Python Dictionary. But I have this challenge: I want to be able to right click in the entry widget and paste keys as well as right click in the output widget and copy values. I'm only able to do so with keyboard shortcut; for convenience sake, I want to be able to do so with the mouse. Thanks. Below is the code:
from tkinter import *
import tkinter. messagebox
root=Tk()
root.geometry('250x250')
root.title("Meta' Translator")
root.configure(background="#35424a")
from playsound import playsound
#Entry widget object
textin = StringVar()
#press ENTER key to activate translate button
def returnPressed(event):
clk()
def clk():
entered = ent.get().lower() #get user input and convert to lowercase
output.delete(0.0,END)
if len(entered) > 0:
try:
textin = exlist[entered]
except:
textin = 'Word not found'
output.insert(0.0,textin)
def play():
text = output.get("0.0", "end").strip("\n")
if text == "əsɔ́":
playsound("hoe.mp3")
elif text == "jam":
playsound("axe.mp3")
elif text == "ɨghə́":
playsound("eye.mp3")
else:
# If there is no sound file for the translation:
playsound("eze.mp3")
#heading
lab0=Label(root,text='Translate English Words to Meta\'',bg="#35424a",fg="silver",font=
('none 11 bold'))
lab0.place(x=0,y=2)
#Entry field
ent=Entry(root,width=15,font=('Times 18'),textvar=textin,bg='white')
ent.place(x=30,y=30)
#focus on entry widget
ent.focus()
#Search button
but=Button(root,padx=1,pady=1,text='Translate',command=clk,bg='powder blue',font=('none 18
bold'))
but.place(x=60,y=90)
#press ENTER key to activate Translate button
root.bind('<Return>', returnPressed)
#output field
output=Text(root,width=15,height=1,font=('Times 18'),fg="black")
output.place(x=30,y=170)
#play button
play_button=Button(root,padx=1,pady=1,text='Play',command=play,bg='powder blue',font=('none
10 bold'))
play_button.place(x=100,y=210)
#prevent sizing of window
root.resizable(False,False)
#Dictionary
exlist={
"hat":"ɨ̀də̀m",
"hoe":"əsɔ́",
"honey":"jú",
"chest":"ɨgɔ̂",
"eye":"ɨghə́",
"ear":"ǝ̀tǒŋ",
"axe":"jam"
}
root.mainloop()
Since your code has a lot of dependency, it cannot be run on another system, so here is a common example which you should be able to implement to your code easily:
from tkinter import *
root = Tk()
def popup(event):
try:
menu.tk_popup(event.x_root,event.y_root) # Pop the menu up in the given coordinates
finally:
menu.grab_release() # Release it once an option is selected
def paste():
clipboard = root.clipboard_get() # Get the copied item from system clipboard
e.insert('end',clipboard) # Insert the item into the entry widget
def copy():
inp = e.get() # Get the text inside entry widget
root.clipboard_clear() # Clear the tkinter clipboard
root.clipboard_append(inp) # Append to system clipboard
menu = Menu(root,tearoff=0) # Create a menu
menu.add_command(label='Copy',command=copy) # Create labels and commands
menu.add_command(label='Paste',command=paste)
e = Entry(root) # Create an entry
e.pack(padx=10,pady=10)
e.bind('<Button-3>',popup) # Bind a func to right click
root.mainloop()
I have explained it with comments to understand on-the-go, nothing complicated. The menu just pops up when you right click on the entry as the function is binded to the entry alone. I think, without clipboard_clear() it would append all the items in the tkinter clipboard to the system clipboard.
I'm writing a program in tkinter using Progressbar. But there is a problem when I added stop function it doesn't work. When I press "stop" button nothing happens, it should stop loading progressbar. I use Python version 3.8. The code below:
from tkinter import *
from tkinter import ttk
import time
root = Tk()
def run():
pb['maximum']=100
for i in range(101):
time.sleep(0.05)
pb['value']=i
pb.update()
def stop():
pb.stop()
runbutt = Button(root,text="Runprogr",command=run)
runbutt.pack()
stopbutt = Button(root,text="Stopbut",command=stop)
stopbutt.pack()
pb = ttk.Progressbar(root,length=300,orient="horizontal")
pb.pack()
root.geometry("300x300")
root.mainloop()
The cause is that pb.stop couldn't stop the function in run.it will also increase by itself.
You could use .after(ms, callback) to add the value(then you no longer need to use time.sleep()).
If you want to stop it,use .after_cancel():
from tkinter import *
from tkinter import ttk
import time
root = Tk()
root.add_value = None
def run():
def add():
if pb['value'] >= 100:
return
pb['value'] += 1
root.add_value = root.after(50, add)
if root.add_value: # to prevent increasing the speed when user pressed "Runprogr" many times.
return
root.add_value = root.after(50, add)
def stop():
if not root.add_value: # to prevent raising Exception when user pressed "Stopbut" button many times.
return
root.after_cancel(root.add_value)
root.add_value = None
runbutt = Button(root, text="Runprogr", command=run)
runbutt.pack()
stopbutt = Button(root, text="Stopbut", command=stop)
stopbutt.pack()
pb = ttk.Progressbar(root, length=300, orient="horizontal")
pb.pack()
root.geometry("300x300")
root.mainloop()
I want to create a message box that confirms the intent to delete.
def delete_action(self):
s_id = self.selected_ID_entry.get()
s_name = self.seletedEntry.get()
answer = messagebox.askquestion("Delete?","Are you sure you want to delete {}".format(s_name), icon='warning')
if answer == 'yes':
#deleted function here
else:
#not deleted function here
How to highlight the "No" button instead of the "Yes" button?
You can set a default value as a keyword argument; something like this:
import tkinter as tk
from tkinter import messagebox
def quid():
messagebox.askyesno("What", "What???????????", default='no')
root = tk.Tk()
ask = tk.Button(root, text='what?', command=quid)
ask.pack()
root.mainloop()