Im very new to Python and trying to set text to a Text field.
But its not going so well. i've followed many tutorials and written the exact same code. but it still not works.
what am i doing wrong ?
def initGUI():
global root,TextField
root = Tkinter.Tk();
TextField = Tkinter.Text(root, width = 50, height= 10);
TextField.pack(side=Tkinter.LEFT,pady=(0,5), expand=Tkinter.YES, fill=Tkinter.BOTH);
Tkinter.mainloop();
def main():
initGUI()
global TextField
TextField.insert(INSERT,"Hello ?") # Tried Tkinter.INSERT / "1.0"
import Tkinter
main()
Im running Python 2.7.5
Solved it by myself.
The mainloop was accidently indented to initGui.
That ment it was not able to change the text at all.
Related
I ran into a probleme when coding a bigger project (at least for me as an absolute newby). I want to open a new tk-window with some text and an image by pressing a Button from another tk-window. I created a code for demonstration.
import tkinter as tk
def fct():
testwin = tk.Tk()
testbutt1 = tk.Button(testwin, text="Button1").pack()
img = tk.PhotoImage(master=testwin,file="picture.png")
imglabel = tk.Label(root,image=img)
imglabel.pack()
testbutt2 = tk.Button(testwin, text="Button2").pack()
testwin.mainloop()
root = tk.Tk()
picbutt = tk.Button(root,text="Exit",command=fct).pack()
label = tk.Label(root)
label.after(5000, fct)
root.mainloop()
This code throws error: "_tkinter.TclError: image "pyimage1" doesn't exist"
When I exchange
img = tk.PhotoImage(master=testwin,file="picture.png")
to
img = tk.PhotoImage(testwin,file="picture.png")
I get error: "images may not be named the same as the main window"
Changing import tkinter as tk to from tkinter import * sadly doesn't change anything either. It also doesnt matter if fct() is called by pressing the button or waiting 5 seconds (label.after(5000, fct))
Python stops executing code at this point. Meaning, testbutt1 shows up, testbutt2 does not.
Hope this explaination is enough to describe the probleme. Thanks for your answers :)
Question
I am trying to make a text editor in Tkinter. If a large single-line file is opened, it lags massively and stops responding. Is there a way to set a wrap length for a text widget? I have scroll bars and I don't want to have the characters wrap at the end of the text box. I want it to wrap after a certain number of characters.
Is this possible?
If so, how can I do it?
I am using Python 3.9.6 on 64-bit Windows 10.
What I have tried
I have tried using wraplength= in the function, but that doesn't work. I have also searched for this question and found nothing.
Code
from tkinter import *
root = Tk()
root.title('Notpad [new file]')
root.geometry('1225x720')
txt = Text(root,width=150,height=40,wrap=NONE)
txt.place(x=0,y=0)
#Buttons here
scr = Scrollbar(root)
scr.pack(side='right',fill='y',expand=False)
txt.config(yscrollcommand=scr.set)
scr.config(command=txt.yview)
scr1 = Scrollbar(root,orient='horizontal')
scr1.pack(side='bottom',fill='x',expand=False)
txt.config(xscrollcommand=scr1.set)
scr1.config(command=txt.xview)
root.mainloop()
There is no wraplength option in tkinter Text widget. However you can simulate the effect using rmargin option of tag_configure().
Below is an example with a custom text widget using rmargin option:
import tkinter as tk
from tkinter import font
class MyText(tk.Text):
def __init__(self, master=None, **kw):
self.wraplength = kw.pop('wraplength', 80)
# create an instance variable of type font.Font
# it is required because Font.measure() is used later
self.font = font.Font(master, font=kw.pop('font', ('Consolas',12)))
super().__init__(master, font=self.font, **kw)
self.update_rmargin() # keep monitor and update "rmargin"
def update_rmargin(self):
# determine width of a character of current font
char_w = self.font.measure('W')
# calculate the "rmargin" in pixel
rmargin = self.winfo_width() - char_w * self.wraplength
# set up a tag with the "rmargin" option set to above value
self.tag_config('rmargin', rmargin=rmargin, rmargincolor='#eeeeee')
# apply the tag to all the content
self.tag_add('rmargin', '1.0', 'end')
# keep updating the "rmargin"
self.after(10, self.update_rmargin)
root = tk.Tk()
textbox = MyText(root, width=100, font=('Consolas',12), wrap='word', wraplength=90)
textbox.pack(fill='both', expand=1)
# load current file
with open(__file__) as f:
textbox.insert('end', f.read())
root.mainloop()
Note that I have used after() so that even there are changes on the content, the rmargin option is applied to updated content.
Note also that it may not be an efficient way, but it shows a possible way.
I'm making an mp3 player in Python using tkinter and pygame. I'm completely new to coding and this in one of the first projects i'm working on. This is learning by doing. I'm trying to get the pause button to pause and unpause. All it does now is pause.
Can I use an if else statement for this? I have google back and forward for two days and tried many different solutions, but none of them have worked. This is what the code looks like now.
self.pauseButton = Button(self, text = 'Pause', command = self.pause)
def pause(self):
pygame.mixer.music.pause()
pygame.mixer.music.unpause()
You can use the text of the button for your advantage.
self.toggleVolumeButton = Button(self, text = 'Pause', command = self.toggleVolume)
def toggleVolume(self):
if self.toggleVolumeButton['text'] == 'Pause':
pygame.mixer.music.pause()
self.toggleVolumeButton['text'] = 'Unpause'
elif self.toggleVolumeButton['text'] == 'Unpause':
pygame.mixer.music.unpause()
self.toggleVolumeButton['text'] = 'Pause'
About accessing the text of a button you can use any of the methods from this question. I chose dictionary one.
As you can guess, there are multiple ways of accomplishing this task. This is just one of the ways.
I have just started to create a simple text editor. I have already bound a couple of functions to certain keypresses and now I'm trying to add a function that operates on the Return delete being pressed. The aim is to remove the last character entered into the text widget. Here is my code:
from tkinter import *
from tkinter import filedialog
import os
root = Tk()
root.geometry('{}x{}'.format(500, 500))
def addchar(event):
w.insert(END, event.char)
def deletechar(event):
current = w.get()
new = current[:-1]
w.delete(0,END)
w.insert(END, new)
def savefile(event):
file = filedialog.asksaveasfilename(defaultextension=".txt")
if file is None:
return
text2save = str(w.get())
file.append(data)
file.close()
w = Entry(root, bd=1)
w.pack()
w.place(x=0, y=0, width=500)
root.bind("<Key>", addchar)
root.bind("<BackSpace>", deletechar)
root.bind("<Control-s>", savefile)
root.bind("<Return>", newline)
root.mainloop()
The issue I'm having is that nothing is removed upon pressing delete to remove the last character entered. Any help appreciated. P.S. Ive tried adding a savefile function to save the text to a file but it doesn't work if anyone can help there also, it would again be appreciated :)
I didn't try to run your code right know because I'm running out of time. However, first of all, you should not use pack and place geometry manager in the same Toplevel, you should only use one. Second, in your savefile function, you did not open the file, so your file variable is only a string. You should use something like file = open(file).
I have been developing an IDE for Python, and I have been wondering about saving myself a lot of time by integrating the colorDelegator module from IDLE.
Is it possible to make use of it, and how would I go about doing so? (with the tkinter text widget).
This is the example that is at the bottom of ColorDelegator.py:
def main():
from idlelib.Percolator import Percolator
root = Tk()
root.wm_protocol("WM_DELETE_WINDOW", root.quit)
text = Text(background="white")
text.pack(expand=1, fill="both")
text.focus_set()
p = Percolator(text)
d = ColorDelegator()
p.insertfilter(d)
root.mainloop()