Python3 和 Tkinter - 无法分配 27 个字节

Ris*_*sso 5 python tkinter

在我的一段代码中,我的脚本生成一个字符串以将其复制到一个 scolled 文本小部件中。如果字符串的大小不是很重,这个过程没有任何问题,但是当字符串很重时,脚本不能将它粘贴到滚动的文本小部件中。当它发生时,脚本会崩溃,并且终端中会出现一条错误消息:(unable to alloc 27 bytes这不是异常事件)。

在崩溃之前,我通过sys.getsizeof函数获得了字符串的字节大小,它是 230031360 字节(230 MB)。

在这些情况下,用户可以解决选择在文本文件中写入输出消息的问题,但是如果用户尝试在 scolled 文本小部件中写入一个粗字符串怎么办?在这种特定情况下,我很想显示一个消息框来建议用户将输出写入文本文件,但是我如何理解脚本是否可以在滚动文本小部件中写入字符串?Python中字符串的字节限制是多少?

更新:

我写了一个例子来告诉你问题发生在哪里。主窗口将在大约两分钟内崩溃并在终端中显示错误消息unable to alloc 28 bytes

from tkinter import *
from tkinter import ttk, scrolledtext
import ipaddress

def GiveMeHosts():
    ls = []
    for host in ipaddress.ip_network("10.0.0.0/8").hosts():
        ls.append(str(host))
    return ls

parent = Tk()
parent.geometry("400x350")
parent.title("The window will crash..")

MyWidget=scrolledtext.ScrolledText(parent, wrap=WORD, width=36, height=14, font=("Segoe UI", 9), state="normal")
MyWidget.pack()

parent.update()

# the string "hosts" is too long, and "MyWidget" can't manage it!
hosts = "\n".join(GiveMeHosts())
MyWidget.insert("1.0", hosts) # it makes the script to crash

parent.mainloop()
Run Code Online (Sandbox Code Playgroud)

Ron*_*ald 1

我运行了你的代码,虽然花了相当长的时间,但它最终确实将所有 IP 地址放入了滚动文本框中。没有错误,也没有崩溃。顺便说一句:unable to alloc 28 bytes,这正是最后两个 ip 地址的大小?!?(10.255.255.253 10.255.255.254)。

我又向前迈出了一步。其实就是两步。尝试运行相同的代码,但将返回值相乘ls *= 5。结果仍然有效,没有崩溃。同时ls其大小为1790312344 bytes (1.67 GB).

然而ls *=10ls现在的大小为2545286976 bytes (2.37 GB),它最终确实因以下回溯而崩溃:

Traceback (most recent call last):
  File "F:\pybin\StackOverflow\so.py", line 28, in <module>
    MyWidget.insert("1.0", hosts) # it makes the script to crash
  File "C:\Program Files\Python36\lib\tkinter\__init__.py", line 3266, in insert
    self.tk.call((self._w, 'insert', index, chars) + args)
OverflowError: string is too long
Run Code Online (Sandbox Code Playgroud)

总而言之,似乎确实存在限制,但该限制很可能取决于系统。至少,这是我从中得出的结论。