Is there a way to make the scrollbar longer in tkinter? - python

I have a tkinter listbox inside a frame which is inside a canvas. The scrollbar works very well through this code:
messagesList.config(yscrollcommand = scrollbar.set)
scrollbar.config(command=messagesList.yview)
However, I wanted the scrollbar to be longer so that I can actually scroll. I tried things such as making the frame bigger or make it take more space with padx and pady. Is there any way to make the scrollbar longer?
The image of how it currently is:
Complete code:
import tkinter as tk
from tkinter import ttk
import tkinter.font as tkFont
root = tk.Tk()
root.title("Messager")
root.geometry("1300x700")
root.resizable(height = 0, width = 0)
#makes window not resizable
class Elements:
def __init__(self, main):
def sendMessage():
user = userName.get()
message = userMessage.get()
print(user+ " username")
print(message + " message")
theCan = tk.Canvas(main)
titleFrame = tk.LabelFrame(main)
mainFrame = tk.LabelFrame(theCan)
greeting = tk.Label(titleFrame, text="Messager", bg = "#74a5f2", font = (None, 35))
userName = tk.Entry(titleFrame, font = (None, 15))
userName.insert(0, "An Unnamed Scrub")
userMessage = tk.Entry(titleFrame, font = (None, 15))
userMessage.insert(0,"Your Message")
sendButton = tk.Button(titleFrame, command = sendMessage, text = "Send!", bg = "#74a5f2", font = (None, 22))
titleMessage = tk.Label(mainFrame, text = "MESSAGER", bg = "#74a5f2", font = (None, 50))
messagesList = tk.Listbox(mainFrame)
scrollbar = tk.Scrollbar(mainFrame, orient=tk.VERTICAL, relief = 'flat')
messagesList.config(yscrollcommand = scrollbar.set)
scrollbar.config(command=messagesList.yview)
testList = ["apple", "orange","apple", "orange","apple", "orange","apple", "orange","apple", "orange","apple", "orange","apple", "orange"]
for item in testList:
messagesList.insert(tk.END, item)
placeholder = tk.Label(main, text = " ")
placeholder1 = tk.Label(main, text = " ")
placeholder2 = tk.Label(main, text = " ")
placeholder3 = tk.Label(main, text = " ")
placeholder4 = tk.Label(main, text = " ")
placeholder5 = tk.Label(main, text = " ")
placeholder6 = tk.Label(main, text = " ")
placeholder7 = tk.Label(main, text = " ")
placeholder8 = tk.Label(main, text = " ")
placeholder9 = tk.Label(main, text = " ")
placeholder10 = tk.Label(main, text = " ")
placeholder11 = tk.Label(main, text = " ")
placeholder12 = tk.Label(main, text = " ")
placeholder13 = tk.Label(main, text = " ")
placeholder.grid(row = 1, column = 1)
placeholder1.grid(row = 2, column = 2)
placeholder2.grid(row = 3, column = 3)
placeholder3.grid(row = 4, column = 4)
placeholder4.grid(row = 5, column = 5)
placeholder5.grid(row = 6, column = 6)
placeholder6.grid(row = 7, column = 7)
placeholder7.grid(row = 8, column = 8)
placeholder8.grid(row = 1, column = 9)
placeholder9.grid(row = 1, column = 10)
placeholder10.grid(row = 1, column = 11)
placeholder11.grid(row = 1, column = 12)
placeholder12.grid(row = 1, column = 13)
placeholder13.grid(row = 1, column = 14)
#placeholders to move the mainframe frame to the center
titleFrame.grid(row = 1, padx = 20, pady = 20)
greeting.grid(pady = 20)
userName.grid()
userMessage.grid(pady = 20)
sendButton.grid()
mainFrame.grid()
titleMessage.grid(pady = 20)
messagesList.grid()
theCan.grid(row = 1, column = 15, pady = 20)
scrollbar.grid(sticky = "ne", rowspan = 5)
postEverything = Elements(root)
root.mainloop()

As has been said already, you need to place the box and the scroll bar on the same row using grid
messagesList = tk.Listbox(mainFrame)
scrollbar = tk.Scrollbar(mainFrame, orient=tk.VERTICAL, relief = 'flat')
messagesList.config(yscrollcommand = scrollbar.set)
scrollbar.config(command=messagesList.yview)
messagesList.grid(row=0,column=0)
scrollbar.grid(row=0,column=1,sticky = "ns")
Also note that I've changed the sticky attribute to be "ns" which means the scroll bar will stretch to fit the row and match the height of the messagesList widget.

Related

Grid_forget() doesn't seem to forget widgets

I have a problem regarding tkinter's grid_forget() method. I have 2 pages in a notebook and I want to show certain widgets on the second page based off the user's selected options in the first page, I have a multiple choice menu and the grid_forget() method seems to work well until I select 2 or more options from the menu. I tried creating the widgets when an option is selected and place them based on the choice, no luck there, also tried creating them with the rest of the widgets and when the user selected an option I would simply just use grid to place them on the screen, also no luck there. I created a demo below, sorry for potential mistakes.
import tkinter as tk
from tkinter import ttk
SMALL_FONT = ("calibri", 16)
class App(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.notebook = ttk.Notebook(self, height = "900", width = "1600")
self.notebook.grid(row = 0, column = 0)
self.frame_pasul3 = tk.Frame(self.notebook)
self.frame_pasul1 = tk.Frame(self.notebook)
self.notebook.add(self.frame_pasul1, text = "First page")
self.notebook.add(self.frame_pasul3, text = "Second page")
self.first_page()
def first_page(self):
options = ["Urmarire mobiliara",
"Urmarire imobiliara",
"Predarea silita bunuri imobile",
"Predarea silita bunuri mobile",
"Obligatia de a face",
"Executare minori"]
menubutton_modalitate_exec = tk.Menubutton(self.frame_pasul1, text="Alegeti o modalitate de executare",
indicatoron=True, borderwidth=1, fg = "#000000",relief="raised")
menu_modalitate_exec = tk.Menu(menubutton_modalitate_exec, tearoff=False)
menubutton_modalitate_exec.configure(menu=menu_modalitate_exec)
menubutton_modalitate_exec.grid(row = 4, column = 1)
self.modalitate = {}
for choice in options:
self.modalitate[choice] = tk.StringVar()
menu_modalitate_exec.add_checkbutton(label=choice, variable=self.modalitate[choice],
onvalue=1, offvalue=0,
command=self.printValues)
self.second_page()
def second_page(self):
self.frame3_titlu_exec = ttk.Frame(self.frame_pasul3)
self.frame3_titlu_exec.grid()
self.frame3_text = ttk.Frame(self.frame_pasul3)
self.frame3_text.grid()
self.frame3_creante = tk.Frame(self.frame_pasul3)
self.frame3_creante.grid()
self.frame3_reprezentand_obligatia = tk.Frame(self.frame_pasul3)
self.frame3_judecatorie = ttk.Frame(self.frame_pasul3)
self.frame3_judecatorie.grid()
self.frame3_texte = tk.Frame(self.frame_pasul3)
self.frame3_texte.grid()
ttk.Label(self.frame3_titlu_exec, font = SMALL_FONT, text = "Titlu Executoriu").grid(row = 0, column = 0, columnspan = 4 ,pady = 10)
ttk.Button(self.frame3_titlu_exec, text = "Contract de credit.").grid(row = 1, column = 0, padx = 10, ipadx = 15, ipady = 5)
ttk.Button(self.frame3_titlu_exec, text = "Sentinta civila.").grid(row = 1, column = 1, padx = 10, ipadx = 15, ipady = 5)
ttk.Button(self.frame3_titlu_exec, text = "Contract notarial.").grid(row = 1, column = 2,padx = 10, ipadx = 15, ipady = 5)
ttk.Button(self.frame3_titlu_exec, text = "Act de adjudecare.").grid(row = 1, column = 3, padx = 10, ipadx = 15, ipady = 5)
self.entry = tk.Text(self.frame3_text, height = 2, wrap = "word", font = ("Helvetica", 10))
self.entry.grid(row = 0, column = 1, padx = 10, pady = 15)
ttk.Button(self.frame3_text, text = "Incarca titlu").grid(row = 0, column = 2, padx = 10, pady = 15)
ttk.Label(self.frame3_creante, font = SMALL_FONT, text = "Creante").grid(row = 0, column = 0)
self.btn_adauga_creante = ttk.Button(self.frame3_creante, text = "Adauga")
self.btn_adauga_creante.grid(row = 0, column = 3)
self.reprezentand_fapt_label = ttk.Label(self.frame3_judecatorie, font = SMALL_FONT, text = "Ce reprezinta fapta.")
self.reprezentand_fapt_label.grid(row = 2, column = 1)
self.reprezentand_creante = tk.Text(self.frame3_judecatorie, height = 3, width = 70)
self.reprezentand_creante.grid(row = 3 , column = 1, pady = 15)
ttk.Label(self.frame3_texte, font = SMALL_FONT, text = "Judecatorie").grid(row = 4, column = 1)
options_jud = ["optiunea 2.",
"test 3",
"test 4",
"test 5"]
self.judecatorie = ttk.Combobox(self.frame3_texte, values = options_jud)
self.judecatorie.set("Selecteaza o judecatorie.")
self.judecatorie.grid(row = 5, column = 1)
ttk.Button(self.frame3_texte, text = "Pasul 2. Parti dosar.").grid(row = 6, column = 0, padx = 15, ipadx = 15, ipady = 5)
ttk.Button(self.frame3_texte, text = "Pasul 4. Cheltuieli de executare").grid(row = 6, column = 3, ipadx = 15, ipady = 5)
def printValues(self):
for name, var in self.modalitate.items():
if var.get() == "1" and (name == "Predarea silita bunuri imobile" or name == "Predarea silita bunuri mobile" or name == "Obligatia de a face" or name == "Executare minori"):
self.reprezentand_creante_label = tk.Label(self.frame3_judecatorie, font = SMALL_FONT, text = "Ce reprezinta creanta.")
self.reprezentand_creante = tk.Text(self.frame3_judecatorie, wrap = "word", height = 3, width = 70)
self.ok_modalitate_exec = 1
self.reprezentand_creante_label.grid(row = 0, column = 1, padx = 15, pady = 15)
self.reprezentand_creante.grid(row = 1, column = 1, padx = 15, pady = 15)
print("Avem 1 la cele 4", name, var.get())
break
elif var.get() == "0" and (name == "Predarea silita bunuri imobile" or name == "Predarea silita bunuri mobile" or name == "Obligatia de a face" or name == "Executare minori"):
print("Avem 0 la cele 4", name, var.get())
self.ok_modalitate_exec = 0
self.reprezentand_creante_label.grid_forget()
self.reprezentand_creante.grid_forget()
break
if __name__ == "__main__":
main_window = tk.Tk()
app = App(main_window)
app.grid()
main_window.mainloop()

Description photo viewer in GUI - Python

I'm new in Python, I am searching for solution with this error. I got stuck with this assignment.
I'm trying to change the description by each picture but unfortunately I failed.
from tkinter import *
from PIL import Image, ImageTk
root = Tk()
root.title("Image Viewer")
root.config(bg = "Grey")
frame1 = Frame(root, width = 500, height = 325, bg = "Silver")
frame1.pack(side = TOP)
frame2 = Frame(root, width = 500, height = 25, borderwidth= 1, bg = "Grey")
frame2.pack(side = BOTTOM, pady= 2)
# Image:
img1 = ImageTk.PhotoImage(Image.open("dec19.jpg"))
img2 = ImageTk.PhotoImage(Image.open("dec20.jpg"))
img3 = ImageTk.PhotoImage(Image.open("dec21.jpg"))
# Description:
des1= Label(frame1, text = "I am happy this day")
des2= Label(frame1, text = "going somewhere")
des3= Label(frame1, text = "Today is a great day")
# , width = 500, height = 315
num = 1
# List:
img_list = [img1, img2,img3]
des_list = [1 , 2, 3]
# Startup:
my_label = Label(frame1,image = img1)
my_label.pack()
my_des = Label(frame1, text = f"Description{num}")
my_des.pack(side = BOTTOM)
# Definning Command functions:
def close_app():
exit()
def forward(image_num):
global my_label
global prev
global next1
global num
global my_des
global des_list
my_label.pack_forget()
# .grid_forget()
my_label = Label(frame1, image= img_list[image_num-1])
my_label.pack()
my_des.pack_forget()
my_des = Label(frame1, text = f"Description{des_list[image_num-1]}")
my_des.pack()
# .grid(row = 0, column = 0, columnspan = 3)
next1 = Button(frame2, text = "Next", command = lambda: forward(image_num+1))
next1.grid(row = 1, column = 2)
prev = Button(frame2, text = "Previous", command = lambda : back(image_num-1))
prev.grid(row = 1, column = 0)
if image_num == 3:
next1 = Button(frame2, text = "Next", state = DISABLED)
next1.grid(row = 1, column = 2)
prev = Button(frame2, text = "Previous", state = DISABLED, command =lambda : back(2))
prev.grid(row = 1, column = 0)
exits = Button(frame2, text = "Exit", command = close_app)
exits.grid(row = 1, column = 1)
next1 = Button(frame2, text = "Next", command = lambda: forward(2))
next1.grid(row = 1, column = 2)
root.mainloop()
If you want that each description is different you can create a dictionary wher you bind each image index to its description
image_description = {
1 : 'I am happy this day',
2 : "going somewhere",
3: "Today is a great day"
}
Now that you have this dictionary when you call the function that changes the image instead having a static string that changes only the number ( f"Description{des_list[image_num-1]}" ) you can get the datas from the dictionary
so change this 3 lines
my_des.pack_forget()
my_des = Label(frame1, text = f"Description{des_list[image_num-1]}")
my_des.pack()
to this
my_des.configure(text = f"{image_description[image_num]}")

reverse button to switch optionmenu values in tkinter

I am creating a currency converter that asks the user to choose the starting and ending currencies with two optionmenu widgets. The problem I have run into is after the currency has been converted, I want to create a button that reverses the optionmenu values to convert back to the original currency. For example, I originally convert 20 USD to EUR. I want the button to reverse it to convert 20 EUR to USD and reflect the change in the optionmenus. Here is the code I have:
currency_list = []
infile = open('currency_list.txt', 'r')
for currency in infile:
currency_list[:-1]
currency_list.append(currency.strip("\t\n\t"))
initial1 = currency_list[-16] # initially set first option menu to USD from currency list
initial2 = currency_list[43] # initially set second option menu to EUR from currency list
my_list = [currency_list[-16], currency_list[43]]
class CurrencyConverter(tk.Frame):
def reverse(self):
my_list.reverse()
print (my_list)
self.currency_1_menu = tk.OptionMenu(self, self.currency_1, *currency_list)
self.currency_2_menu = tk.OptionMenu(self, self.currency_2, *currency_list)
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
body_color = "white"
body_font_color = "black"
entry_color = body_color
entry_font_color = "gray26"
self.currency_1 = tk.StringVar() # currency to convert from
self.currency_2 = tk.StringVar() # currency to convert to
self.currency_1.set(my_list[0]) # set value from list above
self.currency_2.set(my_list[1]) # set value from list above
self.answer = tk.StringVar() # result from conversion
self.value_id = tk.StringVar() # number user types in to convert from
self.header_text = tk.StringVar() # header to display information
logo = tkinter.PhotoImage(file = "logo_copy.gif") # import logo. Not working!!
label = tk.Label(self,image = logo)
label.config(bg = body_color)
label.grid(row = 0, column = 2, rowspan = 2)
self.header = tk.Label(self, textvariable = self.header_text)
self.result_label = tk.Label(self, textvariable = self.answer, fg = body_font_color)
self.value_entry = tk.Entry(self, textvariable = self.value_id)
self.currency_1_menu = tk.OptionMenu(self, self.currency_1, *currency_list)
self.currency_2_menu = tk.OptionMenu(self, self.currency_2, *currency_list)
self.calculate_button = tk.Button(self, command = self.convert, text = 'calculate')
self.reverse_button = tk.Button(self, command = lambda: self.reverse, text = 'reverse')
home_page_button = tk.Button(self, text = "Home Page", command = lambda: controller.show_frame(StartPage))
self.header.config(bg = body_color, font = ('arial', 12), fg = entry_font_color)
self.result_label.config(font = ('Arial', 36))
self.value_entry.config(font = 'bold', justify = 'center', bg = entry_color, fg = entry_font_color, highlightthickness = 0)
self.currency_1_menu.config(bg = body_color, width = 25, height = 2)
self.currency_2_menu.config (bg = body_color, width = 25, height = 2)
self.result_label.config (bg = body_color)
self.calculate_button.config (bg = body_color, highlightbackground = body_color)
self.reverse_button.config (bg = body_color, highlightbackground = body_color)
self.header.grid(row = 0, column = 0, sticky = 'w')
self.result_label.grid(row = 1, column = 0, sticky = 'w')
self.value_entry.grid(row = 2, column = 0)
self.currency_1_menu.grid (row = 2, column = 1)
self.currency_2_menu.grid (row = 3, column = 1)
self.calculate_button.grid(row = 4, column = 0)
self.reverse_button.grid(row = 2, column = 2, rowspan = 2)
home_page_button.grid(row = 4, column = 1)
def convert(self):
self.currency_1_iso = self.currency_1.get()[0:3]
self.currency_2_iso = self.currency_2.get()[0:3]
url = "https://www.xe.com/currencyconverter/convert/?Amount=" + self.value_id.get() + "&From=" + self.currency_1_iso + "&To=" + self.currency_2_iso
print(url)
if (not os.environ.get('PYTHONHTTPSVERIFY', '') and
getattr(ssl, '_create_unverified_context', None)):
ssl._create_default_https_context = ssl._create_unverified_context
html_code = urllib.request.urlopen(url).read()
self.soup = BeautifulSoup(html_code, 'html.parser')
self.result = self.soup.find('span', {'class': "uccResultAmount"}).string
self.answer.set(self.result + " " + self.currency_2_iso)
self.header_text.set(self.value_id.get() + self.currency_1.get()[5:] + ' equals')
Your current attempt at reverse() creates brand new OptionMenus - and never actually displays them. You don't actually need to touch the OptionMenus themselves, just swap the values in the two variables they are tied to:
temp = self.currency_1.get()
self.currency_1.set(self.currency_2.get())
self.currency_2.set(temp)

Using Python to update labels Tkinter

I am in the process of making a Hangman type game. So far, I have written the CLI version which works well, i'm just porting it over to create a GUI.
I have become stuck :-(. The program is not complete, and there's still more to do but I have two issues. The first is the label update.
When a letter is chosen, it creates enough dashes for the letter, and places this in a label called 'letter'.
When a user enters a letter, it replaces the dashes, however it then adds a new label next to the old label, instead, I would like to replace this label. I have tried using the .set() but this doesn't seem to work.
My second issue, and this is more of a logic error (I think), is that I wanted to keep track of the letters entered so that I could compare this to newly entered letters and alert the user. This works well, however when a letter has been entered it will warn the user even if its the first time it has been typed.
Here's the code:
import tkinter
from tkinter import *
from tkinter import messagebox
import random
guesses = 8
def play():
print("play game")
wordList = ["talking", "dollar","choice", "famous", "define", "features"]
wordChoice = random.choice(wordList)
print(wordChoice)
wordLength = (len(wordChoice))
print(wordLength)
guessedLetters = []
dashes = []
def enterLetter():
print("Guess")
global guesses
print(guessedLetters)
while guesses != 0:
guess = entry.get().lower()
if len(guess) >1:
messagebox.showinfo("Error","Sorry, only one letter at a time")
entry.delete("0","end")
return
elif guess.isalpha() == False:
messagebox.showinfo("Error","Letters only please")
entry.delete("0","end")
return
elif guess in guessedLetters:
messagebox.showinfo("Error","You have already used the letter")
entry.delete("0","end")
return
guessedLetters.append(guess)
print(guessedLetters)
print(guesses)
count = 0
for i in range(wordLength):
if wordChoice[i] == guess:
dashes[i] = guess
count = count +1
letter = Label(play, text = dashes, font = ("Arial",20)).grid(row = 2, column = i+1,padx = 10, pady =10)
if count == 0:
guesses -= 1
if guesses == 0:
print("You have ran out of guesses!")
print("The word was:",wordChoice)
###### Play Game GUI
play = Toplevel()
play.title("Play Hangman!")
label = Label(play, text="HANGMAN", font = ("Arial",16)).grid(row = 0)
label = Label(play, text="Enter your guess >").grid(row = 3, column = 0)
for i in range(wordLength):
dashes.append("-")
letter = Label(play, text = dashes, font = ("Arial",20)).grid(row = 2, column = i+1,padx = 10, pady =10)
entry = Entry(play)
entry.grid(row = 3, column = 1, columnspan = wordLength)
enterButton = Button(play, text = "Enter Guess", width = 15, command = enterLetter).grid(row = 3, column = (wordLength+2))
label = Label(play, text = "Letter used: ").grid(row = 4, columnspan = 2)
label = Label(play, text = "").grid(row= 4, columnspan = 6)
def scores():
print("check scores")
def howToPlay():
print("how to play")
####### Main Menu
root = Tk()
root.geometry("500x300")
root.title("HANGMAN")
label = Label(root, text="HANGMAN", font = ("Arial",30)).grid(row = 0, columnspan = 3)
label = Label(root, text = "Option 1 :", font = ("Arial",12)).grid(row = 1, column = 1)
playButton = Button(root, text = "Play Game", width = 15, command = play).grid(row = 1, column = 2)
label = Label(root, text = "Option 2 :", font = ("Arial",12)).grid(row = 2, column = 1)
instructionsButton = Button(root, text = "How to play", width = 15, command = howToPlay).grid(row = 2, column = 2)
label = Label(root, text = "Option 3 :", font = ("Arial",12)).grid(row = 3, column = 1)
scoresButton = Button(root, text = "View Scores", width = 15, command = scores).grid(row = 3, column = 2)
label = Label(root, text = "Option 4 :", font = ("Arial",12)).grid(row = 4, column = 1)
exitButton = Button(root, text = "Exit", width = 15, command = exit).grid(row = 4, column = 2)
root.mainloop()
You need to configure the Label, not recreate it.
Why do you use a while-loop in enter_letter? Its just run when the Button is clicked, it needs to be an if guesses > 0:
Your program did not terminate when the right word was entered; I added this.
Code:
import tkinter
from tkinter import *
from tkinter import messagebox
import random
guesses = 8
letter = None
def play():
global letter
print("play game")
wordList = ["talking", "dollar","choice", "famous", "define", "features"]
wordChoice = random.choice(wordList)
print(wordChoice)
wordLength = (len(wordChoice))
print(wordLength)
guessedLetters = []
dashes = []
play = Toplevel()
play.title("Play Hangman!")
label = Label(play, text="HANGMAN", font = ("Arial",16)).grid(row = 0)
label = Label(play, text="Enter your guess >").grid(row = 3, column = 0)
for i in range(wordLength):
dashes.append("-")
letter = Label(play, text = dashes, font = ("Arial",20))
letter.grid(row = 2, column = i+1,padx = 10, pady =10)
print(letter)
def enterLetter():
print("Guess")
global guesses, letter
print(guessedLetters)
if guesses != 0:
guess = entry.get().lower()
if len(guess) >1:
messagebox.showinfo("Error","Sorry, only one letter at a time")
return
elif guess.isalpha() == False:
messagebox.showinfo("Error","Letters only please")
return
elif guess in guessedLetters:
messagebox.showinfo("Error","You have already used the letter")
return
entry.delete("0","end")
guessedLetters.append(guess)
#print(guessedLetters)
#print(guesses)
print(dashes)
count = 0
for i in range(wordLength):
if wordChoice[i] == guess:
dashes[i] = guess
count += 1
letter.configure(text = dashes)
if count == 0:
guesses -= 1
if "".join(dashes) == wordChoice:
print("succsess!")
play.destroy()
return
if guesses == 0:
print("You have ran out of guesses!")
print("The word was:",wordChoice)
###### Play Game GUI
entry = Entry(play)
entry.grid(row = 3, column = 1, columnspan = wordLength)
enterButton = Button(play, text = "Enter Guess", width = 15, command = enterLetter).grid(row = 3, column = (wordLength+2))
label = Label(play, text = "Letter used: ").grid(row = 4, columnspan = 2)
label = Label(play, text = "").grid(row= 4, columnspan = 6)
def scores():
print("check scores")
def howToPlay():
print("how to play")
####### Main Menu
root = Tk()
root.geometry("500x300")
root.title("HANGMAN")
label = Label(root, text="HANGMAN", font = ("Arial",30)).grid(row = 0, columnspan = 3)
label = Label(root, text = "Option 1 :", font = ("Arial",12)).grid(row = 1, column = 1)
playButton = Button(root, text = "Play Game", width = 15, command = play).grid(row = 1, column = 2)
label = Label(root, text = "Option 2 :", font = ("Arial",12)).grid(row = 2, column = 1)
instructionsButton = Button(root, text = "How to play", width = 15, command = howToPlay).grid(row = 2, column = 2)
label = Label(root, text = "Option 3 :", font = ("Arial",12)).grid(row = 3, column = 1)
scoresButton = Button(root, text = "View Scores", width = 15, command = scores).grid(row = 3, column = 2)
label = Label(root, text = "Option 4 :", font = ("Arial",12)).grid(row = 4, column = 1)
exitButton = Button(root, text = "Exit", width = 15, command = exit).grid(row = 4, column = 2)
root.mainloop()
I hope this helps you.
The reason you cant update your label is because you haven't stored it in any variable. The grid, pack and place functions of the Label object and of all other widgets returns None, therefore when you call:
letter = Label(play, text = dashes, font = ("Arial",20)).grid(row = 2, column = i+1,padx = 10, pady =10)
your label cannot be accessed by variable letter. To fix this you should split it like so:
letter = Label(play, text = dashes, font = ("Arial",20))
letter.grid(row = 2, column = i+1,padx = 10, pady =10)
To update text of that label, you can call .configure(text = 'new text') on it.
# letter = Label(play, text = dashes, font = ("Arial",20)).grid(row = 2, column = i+1,padx = 10, pady =10) #
letter.configure(text = dashes)
As for your second issue, i think you confused while loop and if statement in the function enterLetter. It's called once per click and you only need to check one time if player has ran out of guesses.
if guesses != 0:
...
elif guesses == 0:
....

TKinter math output to canvas.create_text

I am trying to calculate a formula and display its output as a table in TKinter. Since it is not working, I am just trying to get a simple result and print it to a canvas widget. When this gets working I will do the entire loan formula. As it is I get no output in the GUI or in the console.
Is this even possible to place the result of a calculation as text in canvas.create_text?
from tkinter import * # Import tkinter
width = 500
height = 500
class MainGUI:
def __init__(self):
window = Tk() # Create a window
window.title(" Loan Schedule ") # Set title
frame1 = Frame(window)
frame1.grid(row = 1, column = 1)
Label(frame1, text = " Loan Amount ").grid(row = 1, column = 1, sticky = W)
self.v1 = StringVar()
Entry(frame1, textvariable = self.v1, justify = RIGHT).grid(row = 1, column = 2)
Label(frame1, text = " Years ").grid(row = 1, column = 3, sticky = W)
self.v2 = StringVar()
Entry(frame1, textvariable = self.v2, justify = RIGHT).grid(row = 1, column = 4)
btCalculate = Button(frame1, text = " Calculate ", command = self.calculate()).grid(row = 1, column = 5, sticky = E)
frame2 = Frame(window)
frame2.grid(row = 2, column = 1)
self.canvas = Canvas(frame2, width = width, height = height, bg = "white")
self.canvas.pack()
self.canvas.create_text(25, 25, text = self.calculate(), tags = "text")
window.mainloop() # Create an event loop
def calculate(self):
result = self.v1.get() + self.v2.get()
print(result)
return result
MainGUI()
command require function name without ()
command = self.calculate
so now it works
from tkinter import * # Import tkinter
width = 500
height = 500
class MainGUI:
def __init__(self):
window = Tk() # Create a window
window.title(" Loan Schedule ") # Set title
frame1 = Frame(window)
frame1.grid(row = 1, column = 1)
Label(frame1, text = " Loan Amount ").grid(row = 1, column = 1, sticky = W)
self.v1 = StringVar()
Entry(frame1, textvariable = self.v1, justify = RIGHT).grid(row = 1, column = 2)
Label(frame1, text = " Years ").grid(row = 1, column = 3, sticky = W)
self.v2 = StringVar()
Entry(frame1, textvariable = self.v2, justify = RIGHT).grid(row = 1, column = 4)
btCalculate = Button(frame1, text = " Calculate ", command = self.calculate).grid(row = 1, column = 5, sticky = E)
frame2 = Frame(window)
frame2.grid(row = 2, column = 1)
self.canvas = Canvas(frame2, width = width, height = height, bg = "white")
self.canvas.pack()
self.canvas.create_text(55, 10, text = self.add_text(), tags = "text")
window.mainloop() # Create an event loop
def calculate(self):
result = int(self.v1.get()) + int(self.v2.get())
self.canvas.create_text(25, 25, text = result, tags = "text")
print(result)
return result
def add_text(self):
return "HELLO WORLD"
MainGUI()
by the way: line below means - run self.calculate() and result assign to command
command = self.calculate()

Categories

Resources