I want to be able to dynamically change the window title based on the data being displayed in the window. I display a window with a selected weather alert. In the window title, I want to put the alert event name. Each selected alert will have its own event name.
I created a small test to show using a variable in the title works.
from tkinter import *
root = Tk()
mytitle='MYTITLE'
root.title(mytitle)
root.mainloop()
However when I apply what I think is the same setup in my popup window I get title "PY_VAR0".
def msgwindow(x):
print('in message window')
alert_info = Toplevel(root) # Child window
alert_info.geometry("600x700") # Size of the window
alert_row = alert_tree.item(alert_tree.focus()) # selected value to display
alert_row_title = tk.StringVar()
alert_row_title.set(alert_row['values'][1])
print('value1:', alert_row['values'][1], 'title:', alert_row_title)
alert_info.title(alert_row_title)
alert_row_value = tk.StringVar()
alert_row_value.set(alert_row['values'][4])
alert_label = tk.Label(alert_info, textvariable=alert_row_value, justify=LEFT)
alert_label.grid(row=1, column=0, sticky=N+W)
I added a 'print' which shows my title variable has the intended value but the same variable used in title shows PY_VAR0
value1: High Surf Advisory title: PY_VAR0
The the data in alert_row_value displays as intended. This must be simple...what am I doing wrong?
alert_info.title() requires a str, not a StringVar. So, you need to use alert_row_title.get() to get a str that you can pass in. So, your code just needs to be:
alert_info.title(alert_row_title.get())
Related
I am creating a GUI in tkinter having a listbox and a Text item in a child window which appears after a button click. Listbox is displaying values of a dict which are basically names of files/directories in disk image.
I want to change the text of Text widget on <ListboxSelect> event and display type or path of selected file.
Now I cant make Text global since it has to appear on child window, so I need a way to access it in event handler of Listbox. Can I give handler reference of Textbox?
Here is my code;
def command(event):
... #Need to change the Text here, how to access it?
def display_info(dict,filename):
child_w = Tk()
listbox = Listbox(child_w)
textview = Text(child_w)
...
listbox.bind(<ListboxSelect>,command)
def upload_file():
window = Tk()
upl_button = Button(command=upload_file)
window.mainloop()
Is there a way to create a textview as global and then change its properties later to be displayed in child_window etc.
Two solutions here that I can think of is to make textview a globalized variable or to pass textview to command() as an argument.
Parameter solution:
def command(event,txtbox):
txtbox.delete(...)
def display_info(dict,filename):
child_w = Tk()
listbox = Listbox(child_w)
textview = Text(child_w)
...
listbox.bind('<ListboxSelect>',lambda event: command(event,textview))
Or simply just globalize it:
def command(event):
textview.delete(...)
def display_info(dict,filename):
global textview
child_w = Tk()
listbox = Listbox(child_w)
textview = Text(child_w)
...
listbox.bind('<ListboxSelect>',command)
While saying all this, it is good to keep in mind that creating more than one instance of Tk is almost never a good idea. Read: Why are multiple instances of Tk discouraged?
I am making a Speed Typing Test script using tkinter just like this website. But I am stuck in making selection to the text when the focus is in another widget.
Is it even possible to do make a selection visible in Text widget
when the focus is in Entry widget?
You can set the exportselection option of the text widget to False. That will prevent the selected text from automatically being associated with the clipboard. It is that automatic association which causes the selection to be removed whenever focus changes.
I figured it out myself that adding tags solves the problem.
text_widget.tag_add('highlight', '1.0', '1.24')
text_widget.tag_config('highlight', background='#0078d7')
Set the exportselection to False and the inactiveselect attribute to the same color of the selectbackground attribute.
Example:
import tkinter as tk
root = tk.Tk()
text = tk.Text(root, exportselection = False)
text.config(inactiveselect = text.cget("selectbackground"))
text.pack(fill = "both", expand = True)
root.mainloop()
Example using class inheritance:
import tkinter as tk
class myText(tk.Text):
def __init__(self, master, **kw):
tk.Text.__init__(self, master = master, **kw)
if 'exportselection' not in kw.keys():
self['exportselection'] = False
if 'inactiveselect' not in kw.keys():
self['inactiveselect'] = self['selectbackground']
root = tk.Tk()
text = myText(root)
text.pack(fill = "both", expand = True)
root.mainloop()
This way the Text widget will automatically set the exportselection to false and the inactiveselect to selectbackground if you dont define any value to then.
I am trying to create a browse button in tkinter. I have created the open folder dialog box but when i set it to the button it will exit out of the window.
My ultimate goal is to:
1) click on the button and bring up the file dialogue box
2) select a file
3) insert the file name into an Entry Widget for later use
I should note that I am using multiple window frames for the code that follows is summed up.
import os
import sys
import Tkinter as tk
from tkFileDialog import askopenfilename
def openFile(entryWidgetName):
tk.Tk().withdraw()
filename = askopenfilename()
entryWidgetName.delete(0,tk.END)
entryWidgetName.insert(0,filename)
return
class Welcome():
def __init__(self,master):
self.buttonNewTemplate = tk.Button(self.master, text = 'Create a New Template', command = self.gotoNewTemplate).place(x=100, y=250)
def gotoNewTemplate(self):
root2 = tk.Toplevel(self.master)
newTemplate = NewTemplate(root2)
class NewTemplate():
def __init__(self, master):
#Entry Windows
self.uploadFile = tk.Entry(self.sectionFrame2, width = 80).grid(row=4, column = 1, sticky = 'w')
#Buttons
self.buttonBrowse=tk.Button(self.sectionFrame2, text='Browse', fg='blue', command=lambda:openFile(uploadFile)).grid(row=4, column = 0, padx = 10, sticky = 'w')
Every time I click the browse button the second window destroys itself bringing me back to the main page.
Does anyone have any suggestions?
A tkinter application can only have a single instance of Tk. You are creating at least two: one explicitly in openFile, and one from somewhere else in your code either implicitly or explicitly.
Since the only way to call openFile is from a button click, and the only way to have a button click is to have a button, and the only way to have a button is to already have a root window, you need to remove the statement tk.Tk().withdraw() since that is creating a new root window.
There may be other problems in your code, but it's impossible to know based on the incomplete code in the question.
I need help from you.
I want to code a simple menu with tkinter, but i have problem with that.
What I want to do - In my menu,there are 2 items: "first", "second". When i click on the first, program must write 'The first' and then when I click on the second, it must write second, but the first one there will be not yet.
Can anybody help me? Thx.
I mean something like this
from tkinter import *
root = Tk()
def do_something():
# this function e.g. write 'The first'
pass
def do_something_other():
# this function e.g. write 'The second' (but 'The first' there will be not yet)
main_menu = Menu(root)
root["menu"] = main_menu
submenu1 = Menu(main_menu)
submenu1.add_command(label="Item1", command=do_something)
submenu1.add_command(label="Item2", command=do_something_other)
main_menu.add_cascade(label="Program", menu=submenu1)
My goal is, that the canvas will be changing after clicking on the Item1/Item2
You can use a Tkinter Label widget to display text in your GUI. The Label widget has a method called config that you can use to access options of the widget, to include its text attribute.
Here's a simple example. You'll have to modify it to work with your menus and specific needs:
root = Tk()
def callback(): # this function will access the
label.config(text='Updated Text') # config method of label to change it
label = Label(root, text='Original text') # make the label and set default text
btn = Button(root, text='Change text', command=callback) # make the button, which executes the callback func
label.pack()
btn.pack()
mainloop()
I have a Tix.ComboBox with an editable text field. How do I force the variable holding the value for the text to update?
Let me give a more concrete explanation. I have a combo box and a button. When I click the button, it pops up a message box with the value of the combo box. Let's say the combo box text field currently has the value "thing1". If I type "new" into the box and then click on the button with my mouse, it will pops up the message "thing1". If I type "new" in the box and then tab focus away from the combo box and then click the button the pop up message says "new".
Ho do I force the combo box to update it's value to new without requiring that I tab away from the combo box?
I have included sample code.
import Tix
import tkMessageBox
class App(object):
def __init__(self, window):
window.winfo_toplevel().wm_title("test")
self.window = window
self.combo = Tix.ComboBox(window)
self.combo.insert(Tix.END, 'thing1')
self.combo.insert(Tix.END, 'thing2')
self.combo.entry['state'] = "normal"
self.combo['editable'] = True
self.combo.pack()
button = Tix.Button(window)
button['text'] = "Go"
button['command'] = self.go
button.pack()
def go(self):
tkMessageBox.showinfo('info', self.combo['value'])
if __name__ == '__main__':
root = Tix.Tk()
App(root)
root.mainloop()
woo!
solved it on my own.
Use
self.combo['selection']
instead of
self.combo['value']
NOTE: copy of Moe's answer that can be selected as chosen answer
woo!
solved it on my own.
Use
self.combo['selection']
instead of
self.combo['value']