My program has a library which opens a new window
This is the library (its called make_entry):
from tkinter import *
def Create():
Window = Tk() # window
Window.geometry("900x500+50+50") # heightxwidth+x+y
mainPanel = Canvas(Window, width = 900, height = 500) # main screen
mainPanel.pack()
anyvar = StringVar() # the text in the entry
entry = Entry(mainPanel, width = 40, font = ("Purisa", 12, "bold"), justify = "center", textvariable = anyvar) # the entry
mainPanel.create_window(200, 100, window = entry)
anyvar.set("This doesnt work!!!!!")
Window.mainloop()
#Create()
If I run this library by itself then everything works fine, but when I import it from another program the only thing which doesn't work is anyvar.set("This doesnt work!!!!!").
Here is where I import it: (most of this code is cut out)
from tkinter import *
Window = Tk()
import make_entry
make_entry.Create()
Window.mainloop()
Is there a way to fix this problem without removing any of the windows?
You have two instances of Tk() which confuses Tkinter. I am guessing that the StringVar() is going to the other (first) instance. Instead, pass the only instance to the function, and use a Toplevel for a new window.
from tkinter import *
def Create(root):
window=Toplevel(root)
window.geometry("900x500+50+50") # heightxwidth+x+y
mainpanel = Canvas(window, width = 900, height = 500) # main screen
mainpanel.pack()
anyvar = StringVar() # the text in the entry
entry = Entry(mainpanel, width = 40, font = ("Purisa", 12, "bold"), justify = "center", textvariable = anyvar) # the entry
mainpanel.create_window(200, 100, window = entry)
anyvar.set("This doesnt work!!!!!")
and
from tkinter import *
Window = Tk()
import make_entry
make_entry.Create(Window)
Window.mainloop()
Related
I was able so successfully place the input module earlier but now when I try to implement code to use 'Enter' to accept the input I'm not even able to get it to pack. If anyone can help me it would be thoroughly appreciated. Eventually I am trying to make it so that whatever typed ends up being incrementally placed as a title in a column centered to the left of the entry widget but I will work on that later. (this is the UI for a text adventure game)
Below is the code I have so far
#imports
import time, os, sys, logging
from pynput import *
from tkinter import Button
from tkinter import *
import customtkinter
import tkinter.font as font
from tkinter import simpledialog
import tkinter
import time
import tkinter as tk
userin = ''
#graphics
the_path_text = '''
┏┓┏┓╋╋╋╋╋╋╋╋┏┓┏┓
┃┗┫┗┳━┓┏━┳━┓┃┗┫┗┓
┃┏┫┃┃┻┫┃╋┃╋┗┫┏┫┃┃
┗━┻┻┻━┛┃┏┻━━┻━┻┻┛
╋╋╋╋╋╋╋┗┛'''
#window
customtkinter.set_appearance_mode("dark")
customtkinter.set_default_color_theme("dark-blue")
root = customtkinter.CTk()
root.geometry("800x520")
root.resizable(width = False, height = False)
root.title('The Path')
photo = PhotoImage(file = "D:\\pathpic.png")
root.iconphoto(False, photo)
myfont = ("Roboto Mono",30)
frame = customtkinter.CTkFrame(master = root)
frame.pack(pady = 20, padx = 60, fill = 'both', expand = True)
#splash/start screen
#loading
label = customtkinter.CTkLabel(root, text="Loading", font= ('Roboto', 20))
label.pack()
# Incrementally add dots
for i in range(3):
label.configure(text="Loading" + "." * (i + 1))
time.sleep(.5)
root.update()
# Clear the label text
label.configure(text="")
# Incrementally add dots again
for i in range(3):
label.configure(text="Loading" + "." * (i + 1))
time.sleep(.5)
root.update()
label.configure(text=" ")
#splash logo
label_path_logo = customtkinter.CTkLabel(master=frame, text= the_path_text, font = ('Roboto', 20))
label_path_logo.pack(pady =12, padx = 10)
#clearing splash/ main game loop
start = 0
def clear_start():
time.sleep(.2)
global frame, root
frame.destroy()
frame = Frame(root)
frame.pack()
start_button.destroy()
start = 1
#main game
start_button = customtkinter.CTkButton(master=root, text="Enter the path", command = clear_start)
start_button.pack(padx = 6, pady=20)
while start == 1:
#main text console
main_entry = root.entry = customtkinter.CTkEntry(root, textvariable=userin, placeholder_text="Enter Command")
main_entry.pack(side = BOTTOM,fill = BOTH, pady = 5, padx = 200 )
def process(event=None):
content = main_entry.get() # get the contents of the entry widget
print(content) # for example
main_entry.bind('<Return>', process)
root.mainloop()
I have several larger tkinter / python program which I would like to incorporate into one program which would clear a frame when another program is called; each program currently being inside a function (I probably should use classes eventually when I understand them) and each of these function being displayed on a form being cleared of widgets from the previous if any do exist.
The code below is just a small trial for me to understand how to do this, but it's not working.
When I invoke the widget.destroy() function, it removes the frame (DisplayFrame) and does not clear the widgets inside it and hence not displaying the new widgets.
here is the current trial code:
#!/usr/bin/env python3
import tkinter as tk
from tkinter import *
from tkinter import ttk
#import pandas as pd
import MultiTempsP3
import datetime, time
from tkinter import messagebox
import sqlite3
from tkinter import colorchooser
from configparser import ConfigParser
import os
import csv
if os.environ.get('DISPLAY','') == "":
print('no display found.Using :0.0')
os.environ.__setitem__('DISPLAY',':0.0')
root = tk.Tk()
root.title("Kombucha Program")
root.geometry("1400x800")
root.minsize(width=900, height=600)
#root.maxsize(width=1400, height = 900)
root.grid_rowconfigure(3, weight=1)
root.grid_columnconfigure(2, weight=1)
root.configure( bg = '#000080' )
DisplayFrame = tk.Frame(root, width=1200, height = 630, bg = 'yellow') #0059b3')
DisplayFrame.grid(column=0,row=1, sticky = N, in_ = root)
rightFrame = tk.Frame(root, width = 120, height = 390, bg = 'white') # #000080
rightFrame.grid(column = 1, row = 0, pady = 10, padx = 10)
lblFrame = tk.Frame(root, height = 70, width = 670, bg = 'black')
lblFrame.grid(column = 0, row = 0, sticky =N, in_ = root)
##'W' stands for West = WrightFrmae (west fframe on the right of screen
#WrightFrame = tk.Frame(rightFrame, width = 70, height = 300, bg = 'green') # #000080
#WrightFrame.grid(column = 0, row = 1)
WidgetFrame = tk.Frame(root, height = 300, width = 120, bg = 'red') # #000080
WidgetFrame.grid(column=0,row=2, pady = 30)
fromTemp = MultiTempsP3.temps("65cd6bd")
lblTemp = Label(rightFrame, text=fromTemp).grid(row=1,column=0,pady=0 )
#lblTemp.pack()
def clearDisplayFrame():
for widgets in DisplayFrame.winfo_children():
widgets.destroy()
###***### - This section is in the right top little frame = rightFrame
state = "yes" ## delete this row and use below state=GPIO when on an RPi
#state = GPIO.input(17)
if state:
state_17="GPIO_17 (HeatPad) is On "
else:
state_17="GPIO_17 (HeatPad) is Off "
lblHeatPad = Label(rightFrame, text=state).grid(row=3,column=0,pady=0 ) #shows as text in the window
#lblHeatPad.pack() #organizes widgets in blocks before placing them in the parent.
###***### End of rightFrame widgets
def func_quit():
root.destroy()
def openData():
clearDisplayFrame()
print("I am inside openData()")
lbltrial=tk.Label(DisplayFrame,text="trial").grid(row=3, column=2)
def func_Temps():
clearDisplayFrame()
print("I am inside func_Temps()")
#DisplayFrame = tk.Frame(root, width=1200, height = 630, bg = 'yellow') #0059b3')
#DisplayFrame.grid(column=0,row=1, sticky = N, in_ = root)
lblSomething = tk.Label(DisplayFrame, text = "Open Temps").grid(row=2,column=2)
###***### This section is top of left = lblFrame
exitButton = tk.Button(lblFrame, text="Quit the Program", width = 12, command=root.destroy, bg= "magenta")
exitButton.grid(row = 0, column = 0, columnspan = 1, pady = 5, padx = 5)
dataButton = Button(lblFrame, text="Open Dates Window", command=openData).grid(row=0, column=1) ## the open refers to the above function
tempsButton= Button(lblFrame, text="Open Temps Info", command=func_Temps).grid(row=0, column=2)
###***### End of top left widget in lblFrame
mainloop()
As an answer, here is an approach that uses 2 frame and switches between them in the click of the switch. This is the way usually switching between frame is implemented in procedural programming, AFAIK:
from tkinter import *
root = Tk()
def change(frame):
frame.tkraise() # Raising the passed frame
window1 = Frame(root)
window2 = Frame(root)
window1.grid(row=0,column=0) # Grid in the same location so one will cover/hide the other
window2.grid(row=0,column=0)
# Contents inside your frame...
Label(window1,text='This is page 1',font=(0,21)).pack()
Label(window2,text='This is page 2',font=(0,21)).pack()
# Buttons to switch between frame by passing the frame as an argument
Button(root,text='Page 1',command=lambda: change(window1)).grid(row=1,column=0,stick='w')
Button(root,text='Page 2',command=lambda: change(window2)).grid(row=1,column=0,stick='e')
root.mainloop()
So instead of destroying all the items inside your frame, you should just raise the other frame, as destroyed widgets cannot be brought back.
Is it possible to add an image to a combobox in tkinter?
I tried the following, but I already expected it to not work.
import tkinter as tk
from tkinter import ttk
from tkinter import *
# Creating tkinter window
window = tk.Tk()
window.title('Combobox')
window.geometry('1440x900')
main_canvas = Canvas(
window,
bg = "#FFFFFF",
height = 900,
width = 1440,
bd = 0,
highlightthickness = 0,
relief = "ridge"
)
main_canvas.place(x = 0, y = 0)
main_button_image_1 = PhotoImage(
file="button_1.png")
n = tk.StringVar()
monthchoosen = ttk.Combobox(window, width = 27, textvariable = n, image=main_button_image_1)
# Adding combobox drop down list
monthchoosen['values'] = ('new')
monthchoosen.place(
x=10.0,
y=826.0,
width=55.0,
height=55.0
)
monthchoosen.current(0)
window.mainloop()
Basically I want to make the combobox look a bit better and the easiest way would be to design an image and add it to the combobox.
PS:
I just copied real quick a few thinks, so please don't mind the variable names.
No, the ttk.Combobox widget does not support images.
I am trying to code a game for my school assignment. In this game, I wanted to have a mute button so I have made a button on top of a label frame and place it in a label. I don't know what is wrong with it but the image does not show up. I have tried to create a local copy by assigning it to a temp variable and yet it still doesn't show up. Here's my code:
from tkinter import ttk
from PIL import Image, ImageTk
root = Tk()
topFrame =Frame(root, width=500, height=50,)
topFrame.grid(row=0, column= 0)
btnframe = LabelFrame(topFrame, width = 20, height = 20)
btnframe.place(x = 450, y= 5 )
mute_image = Image.open("pygame/mute.png")
mute_image = mute_image.resize((50,50), Image.ANTIALIAS)
mute_icon = ImageTk.PhotoImage(mute_image)
mute_button = Button( btnframe, width = 50, height = 50, command = Mute, image = mute_icon)
mute_button.image = mute_icon
mute_button.pack()
root.mainloop()
Please go easy on me, this is my first time coding a game ever:)) Thanks in advance:))
Are you getting any error messages. I slightly modified your code and it complained abuot the button callback function was not defined. After I added that it all seems to work.
from tkinter import *
from PIL import Image, ImageTk
root = Tk()
topFrame =Frame(root, width=500, height=50,)
topFrame.grid(row=0, column= 0)
btnframe = LabelFrame(topFrame, width = 20, height = 20)
btnframe.place(x = 450, y= 5 )
def Mute():
pass
mute_image = Image.open("images/beer.png")
mute_image = mute_image.resize((50,50), Image.ANTIALIAS)
mute_icon = ImageTk.PhotoImage(mute_image)
mute_button = Button(btnframe, width=50, height=50,
command=Mute, image=mute_icon)
mute_button.image = mute_icon
mute_button.pack()
root.mainloop()
Using Tkinter in Python I am trying to change what is displayed in a textbox when a button is pressed. My code so far is:
screen = Tk()
text = Text(screen, height = 2, width = 30)
text.pack()
text.insert(END, '-')
def apress():
text.insert(END, 'a')
a = Tkinter.Button (screen, text = 'a', width = 5, command = apress).pack()
mainloop()
When the code is run nothing happens and the debugger will not stop running even if you click 'abort debugging'. Is there a way to fix this?
Here's the working code:
from Tkinter import *
screen = Tk()
text = Text(screen, height = 2, width = 30)
text.pack()
text.insert(END, '-')
def apress():
text.insert(END, 'a')
btn = Button(screen, text = 'a', width = 5, command = apress)
btn.pack()
mainloop()
Changes I made:
Added the import from Tkinter import *
Used Button instead of Tkinter.Button - since we used an wildcard import
Button.pack() separated on a new line
Demo:
Initial view:
Clicked the button several times: