I am trying to build a small GUI for my D&D character but my second attack button does not appear.
Tried to make it read as easy as possible. Its my second try on programming, I find the Tkinter really difficult to work with :(
Written in Python 3:
# Tkinter_buildframe #
root = tk.Tk()
frame = tk.Frame(root)
frame.pack( side = TOP )
frame.pack()
root.geometry("300x200")
# This is the charicter stats #
w = Label(root, text="""
charisma modifier = 4
spellcast attack_bonus = 7
""", font="12")
w.pack()
# Quit_button #
button = tk.Button(frame,
text="QUIT",
fg="red",
command=quit)
button.pack(side=tk.BOTTOM)
# Attack1 eldritch_blast_with_hex #
slogan = tk.Button(frame,
text="Eldritch Blast with Hex",
command=eldritch_blast_with_hex)
slogan.pack(side=tk.LEFT)
root.mainloop()
def popupmsg(msg):
popup = tk.Tk()
popup.wm_title("Eldritch Blast with Hex")
label = ttk.Label(popup, text=msg, font=NORM_FONT)
label.pack(side="top", fill="x", pady=10)
B1 = ttk.Button(popup, text="Okay", command = popup.destroy)
B1.pack()
popup.mainloop()
# Attack2 eldritch_blast_without_hex#
slogan = tk.Button(frame,
text="Eldritch Blast without Hex",
command=eldritch_blast_without_hex)
slogan.pack(side=tk.LEFT)
root.mainloop()
def popupmsg(msg):
popup = tk.Tk()
popup.wm_title("Eldritch Blast without Hex")
label = ttk.Label(popup, text=msg, font=NORM_FONT)
label.pack(side="top", fill="x", pady=10)
B1 = ttk.Button(popup, text="Okay", command = popup.destroy)
B1.pack()
You have multiple root.mainloop() in the code, it just pauses the code from continuing the execution of rest of the code. So remove one of the root.mainloop() and place one at the end of the code.
Related
The code below represents my first steps into making a calculator on python using tkinter. The idea is to put the numbers on a grid accordingly, and then make the all of the necessary adjustments. The problem here is that I get the following error:
_tkinter.TclError: cannot use geometry manager grid inside . which already has slaves managed by pack
I'm aware that this is because of the canvas.pack(), but isn't it necessary for the background? How can I separate them in the most efficient way possible? On that note, is there a way to put all of the buttons/grids together using fewer lines of code? Thanks in advance.
from tkinter import *
#Creating the window function (?)
window = Tk()
#Creating a frame and a background for the calculator
canvas = tk.Canvas(window, height=700, width=700, bg="#83CFF1")
canvas.pack()
frame = tk.Frame(window, bg="white")
frame.place(relwidth=0.7, relheight=0.7, relx=0.15, rely=0.15)
#Creating the buttons for the calculator
button1 = Label(window, text="1")
button2 = Label(window, text="2")
button3 = Label(window, text="3")
button4 = Label(window, text="4")
button5 = Label(window, text="5")
button6 = Label(window, text="6")
button7 = Label(window, text="7")
button8 = Label(window, text="8")
button9 = Label(window, text="9")
button0 = Label(window, text="0")
#Adding it to the screen
button1.grid(row=0, column=0)
button2.grid(row=0, column=1)
button3.grid(row=0, column=2)
button4.grid(row=1, column=0)
button5.grid(row=1, column=1)
button6.grid(row=1, column=2)
button7.grid(row=2, column=0)
button8.grid(row=2, column=1)
button9.grid(row=2, column=2)
button0.grid(row=3, column=1)
#Ending the loop (?)
window.mainloop()
Create buttons using Python list comprehension.
For the grid placment use i // 3 (floor division) and i % 3 (modulo) inside a for loop.
Then just simply add the last button manually.
This code below will do the trick:
import tkinter as tk
window = tk.Tk()
frame = tk.Frame(window, bg="white")
frame.place(relwidth=0.7, relheight=0.7, relx=0.15, rely=0.15)
#Creating the buttons for the calculator
buttons = [tk.Button(frame, text = i) for i in range(1, 10)]
for i, button in enumerate(buttons):
button.grid(row = i // 3, column = i % 3)
#Add last button 0
buttons.append(tk.Button(frame, text = 0))
buttons[-1].grid(row=3, column=1)
window.mainloop()
I have created a chat application, in which i use ListBox for showing the chat history. It looks good until I enter a long sting which goes beyond the screen. Is there a way to break the string and show in new line or any other way to show the complete string. I'm new to Tkinter and im not aware of many widgets available.
Here is my sample code
from tkinter import *
class Actions:
def chatUpdate(chat):
chatlist.insert(Actions.chatLast,chat)
Actions.chatLast=Actions.chatLast+1
chatlist.pack( side=LEFT, fill=BOTH)
chatBox.config(command=chatlist.yview)
def callUpdater():
txt=textBox.get()
text_text.set("")
Actions.chatUpdate(txt)
root = Tk()
root.title("Chat App")
frame1 = Frame(root, bd=4)
frame1.pack(side=TOP)
frame2 = Frame(root, bd=4)
frame2.pack(side=TOP)
frame3 = Frame(root, bd=4)
frame3.pack(side=TOP)
# chat box
chatBox = Scrollbar(frame1)
chatBox.pack(side=RIGHT, fill=Y)
chatlist = Listbox(frame1, yscrollcommand = chatBox.set, width=50)
Actions.chatLast=0
Actions.chatUpdate(" ")
# text box
textView = Label(frame2, text="Input: ")
textView.pack(side=LEFT)
text_text = StringVar()
textBox = Entry(frame2, textvariable=text_text, bd=0, width=40, bg="pink")
textBox.pack(side=RIGHT)
# send button
button = Button(frame3, text="Send", fg="black", command=callUpdater)
button.pack(side=TOP)
root.mainloop()
You can replace the Listbox by a Text widget in 'disabled' mode which automatically wraps long lines. You will just need to put the widget back in 'normal' mode each time you insert text:
from tkinter import *
def callUpdater():
text = textBox.get()
textBox.delete(0, 'end')
chat.configure(state='normal')
chat.insert('end', text + '\n')
chat.configure(state='disabled')
root = Tk()
chatBox = Scrollbar(root)
chat = Text(root, wrap='word', state='disabled', width=50,
yscrollcommand=chatBox.set)
chatBox.configure(command=chat.yview)
chat.grid(row=0, columnspan=2, sticky='ewns')
chatBox.grid(row=0, column=2, sticky='ns')
Label(root, text="Input: ").grid(row=1, column=0)
textBox = Entry(root, bd=0, width=40, bg="pink")
textBox.grid(row=1, column=1)
Button(root, text="Send", command=callUpdater).grid(row=2, columnspan=2)
root.mainloop()
By the way, both the Listbox and Text widgets support the index 'end' so you don't have to keep track of how many lines you have inserted.
how do I position my label which says "Question One" in my def new_window() function. As you run it the label is being positioned at the bottom, And i want it to be applied on the top.
from tkinter import *
from tkinter import ttk
#User Interface Code
root = Tk() # Creates the window
root.title("Quiz Game")
def new_window():
newWindow = Toplevel(root)
display = Label(newWindow, width=150, height=40)
message = Label(newWindow, text="Question One", font = ("Arial", "24"))
display.pack()
message.pack()
display2 = Label(root, width=100, height=30, bg='green')
button1 = Button(root, text ="Continue", command=new_window, width=16,
bg="red")
message_label1 = Label(text="A Quiz Game", font = ("Arial", "24"), padx=40,
pady=20)
message_label2 = Label(root, text="Click 'Continue' to begin.",
wraplength=250)
display2.pack()
button1.pack()
message_label1.pack()
message_label2.pack()
root.mainloop() # Runs the main window loop
You are packing in the wrong order. Do not pack display before your message. So just swapping the order will fix the issue.
Here is the code. Replace your def new_window(): with this
def new_window():
newWindow = Toplevel()
message = Label(newWindow, text="Question One", font = ("Arial", "24"))
display = Label(newWindow, width=150, height=40)
message.pack()
display.pack()
pack method just blindly packs the widget into the window. And the next pack will be done below it if there is space. So take care of the order while packing widgets :)
I started using TK in python to build a graphical interface for my program.
I'm not able to fix 2 issues concerning (1) the position of a button in the window and (2) use a value of a radiobutton inside a fucntion.
This is my current code:
root = tk.Tk()
root.title("START")
root.geometry("500x200+500+200")
v = tk.IntVar()
v.set(0) # initializing the choice
my_choise = [
("Basic",1),
("Advanced",2),
('Extreme',3)
]
def ShowChoice():
print(v.get())
tk.Label(root,
text="""Choose your configuration:""",
justify = tk.LEFT,
padx = 20).pack()
val = 0
for val, choise in enumerate(my_choise):
tk.Radiobutton(root,text=choise,padx = 20,variable=v,command=ShowChoice,value=val).pack(anchor=tk.W)
def star_program(value):
os.system("ifconfig")
def open_comments_file():
os.system("gedit /home/user/Desktop/comments.txt")
def open_links_file():
os.system("gedit /home/user/Desktop/links.txt")
frame = tk.Frame(root)
frame.pack()
open_file_c = tk.Button(frame,
text="Comments",
command=open_comments_file)
open_file_f = tk.Button(frame,
text="Links",
command=open_links_file)
button = tk.Button(frame,
text="Start",
command=star_program(v.get()))
button.pack(side=tk.LEFT)
open_file_f.pack(side=tk.LEFT)
open_file_c.pack(side=tk.LEFT)
slogan = tk.Button(frame,
text="Cancel",
command=quit)
slogan.pack(side=tk.LEFT)
root.mainloop()
I would like that the buttons "Links" and "Comments" were positioned below the radiobutton, one below the other. Now, all buttons are in line, but I would like to have "start" and "cancel" at the bottom of my window.
Then I tried to use the value of the radiobutton (choice) inside the star_program function. It does not work. My idea is, based on the choice selected in the radiobutton, perform different actions when I click the button "start":
def star_program(value):
if value == 0:
os.system("ifconfig")
else:
print "Goodbye"
In addition, concerning "start" button, I have a strange behavior. The program runs "ifconfig" command also if I don't click on "start". And If I click "start" it does not perform any action.
Any suggestion?
Thanks!!!
i'm assuming this is more like what you're after:
root = tk.Tk()
root.title("START")
root.geometry("500x200+500+200")
v = tk.IntVar()
v.set(0) # initializing the choice
my_choise = [
("Basic",1),
("Advanced",2),
('Extreme',3)
]
def ShowChoice():
print(v.get())
tk.Label(root,
text="""Choose your configuration:""",
justify = tk.LEFT,
padx = 20).grid(column=1, row=0, sticky="nesw") # use grid instead of pack
root.grid_columnconfigure(1, weight=1)
val = 0
for val, choise in enumerate(my_choise):
tk.Radiobutton(root,text=choise,padx = 20,variable=v,command=ShowChoice,value=val).grid(column=1, row=val+1, sticky="nw")
def star_program(value):
os.system("ifconfig")
def open_comments_file():
os.system("gedit /home/user/Desktop/comments.txt")
def open_links_file():
os.system("gedit /home/user/Desktop/links.txt")
frame = tk.Frame(root)
frame.grid(column=1, row=4, sticky="nesw")
open_file_c = tk.Button(frame,
text="Comments",
command=open_comments_file)
open_file_f = tk.Button(frame,
text="Links",
command=open_links_file)
button = tk.Button(frame,
text="Start",
command=lambda: star_program(v.get()))
# use lambda to create an anonymous function to be called when button pushed,
needed for functions where arguments are required
button.grid(column=2, row=3, sticky="nesw")
open_file_f.grid(column=1, row=1, sticky="nesw")
open_file_c.grid(column=1, row=2, sticky="nesw")
slogan = tk.Button(frame,
text="Cancel",
command=quit)
slogan.grid(column=4, row=3, sticky="nesw")
root.mainloop()
The problem with the "start" button is due to the function definition.
This is the right code that does not trigger any action if you don't click the button:
button = tk.Button(frame,
text="Start",
command=star_program)
from Tkinter import *
import random
menu = Tk()
subpage = Tk()
entry_values = []
population_values = []
startUpPage = Tk()
def main_menu(window):
window.destroy()
global menu
menu = Tk()
frame1 = Frame(menu)
menu.resizable(width=FALSE, height=FALSE)
button0 = Button(menu, text="Set Generation Zero Values", command=sub_menu(menu))
button1 = Button(menu, text="Display Generation Zero Values")
button2 = Button(menu, text="Run Model")
button3 = Button(menu, text="Export Data")
button4 = Button(menu, text="Exit Program", command=menu.destroy)
button0.grid(row=0, column=0, sticky=W)
button1.grid(row=2, column=0, sticky=W)
button2.grid(row=3, column=0, sticky=W)
button3.grid(row=4, column=0, sticky=W)
button4.grid(row=5, column=0, sticky=W)
menu.mainloop()
def sub_menu(window):
global subpage
window.destroy()
subpage = Tk()
subpage.resizable(width=FALSE, height=FALSE)
#defining sub page items
button5 = Button(subpage, text="Save Generation Data",command = main_menu(subpage))
juveniles_label0 = Label(subpage,text="Juveniles")
adults_label1 = Label(subpage,text="Adults")
seniles_label2 = Label(subpage,text="Seniles")
population_label3 = Label(subpage,text="Popultation")
survival_rate_label4 = Label(subpage,text="Survival Rate (Between 0 and 1)")
entry0 = Entry(subpage)
entry1 = Entry(subpage)
entry2 = Entry(subpage)
entry3 = Entry(subpage)
entry4 = Entry(subpage)
entry5 = Entry(subpage)
button4.grid(row=1, column= 6, sticky=E)
juveniles_label0.grid(row=0, column=1)
adults_label1.grid(row=0, column=2)
seniles_label2.grid(row=0, column=3)
population_label3.grid(row=1, column=0)
survival_rate_label4.grid(row=2, column=0)
entry0.grid(row=1, column=1)
entry1.grid(row=1, column=2)
entry2.grid(row=1, column=3)
entry3.grid(row=2, column=1)
entry4.grid(row=2, column=2)
entry5.grid(row=2, column=3)
#add entry 6 7 8
subpage.mainloop()
main_menu(subpage)
main_menu(startUpPage)
I'm very new to coding and stackoverflow. I am trying to create a GUI that has a main page which will be opened first and a sub page which will be opened by clicking a button which will be stored in the main page. my issue is that I have no clue why it isn't opening my main page. my thought is that it is something to do with the .destroy() or something similar. any help would be much appreciated.
As a general rule, you should create exactly one instance of Tk for the life of your program. That is how Tkinter is designed to be used. You can break this rule when you understand the reasoning behind it, though there are very few good reasons to break the rule.
The simplest solution is to implement your main menu and your sub menu as frames, which you've already done. To switch between them you can simply destroy one and (re)create the other, or create them all ahead of time and then remove one and show the other.
For example, the following example shows how you would create them ahead of time and simply swap them out. The key is that each function needs to return the frame, which is saved in a dictionary. The dictionary is used to map symbolic names (eg: "main", "sub", etc) to the actual frames.
def main_menu(root):
menu = Frame(root)
button0 = Button(menu, text="Set Generation Zero Values",
command=lambda: switch_page("sub"))
...
return menu
def sub_menu(root):
subpage = Frame(root)
button5 = Button(subpage, text="Save Generation Data",
command = lambda: switch_page("main"))
...
return subpage
def switch_page(page_name):
slaves = root.pack_slaves()
if slaves:
# this assumes there is only one slave in the master
slaves[0].pack_forget()
pages[page_name].pack(fill="both", expand=True)
root = Tk()
pages = {
"main": main_menu(root),
"sub": sub_menu(root),
...
}
switch_page("main")
root.mainloop()
For a more complex object-oriented approach see Switch between two frames in tkinter
heres some code that does what you want.. make a window, destroy it when button is clicked and then make a new window...
from Tkinter import *
import random
def main_menu():
global root
root = Tk()
b = Button(root,text='our text button',command = next_page)
b.pack()
def next_page():
global root,parent
parent = Tk()
root.destroy()
new_b = Button(parent,text = 'new Button',command=print_something)
new_b.pack()
def print_something():
print('clicked')
main_menu()
root.mainloop()
parent.mainloop()
ps. ive done this in python3 so keep that in mind though it wouldnt be a problem in my opinion